Jump to content

[1.8] custom Item whith an inventory, weird behaveour mising items


perromercenary00

Recommended Posts

good days

 

again I'm trying to make something a little complicated

i have a guns mod

in order to give to the entities more munition i create a little inventory  like a chess but in the handgun like a backpack with nine slots but with the hability to shoot bullets

to do this i scavenge the code from the dispenser tileentity an make some changes

 

actually most of the code works, if i aim to an entity that holds the  m92 handgun an press NumKeyEnter its open the menu whith the nine slots from the gun hold by the entity.

if i put munition and magazines inside this inventory mi entities are able to use it to reload the gun and keep shooting  so the inventory works and can be recalled by other classes or entities

 

the trouble its if i try to move an item two times in a row this item disappears from the inventory 

lets say i take a bullets Stack from the player inventory  an put it in the slot 0 from the gun inventory  well if i close the inventory and reopen it later everyting works as expected,  at reopen there is a bullet stack in the slot 0 from the gun inventory

 

but if i take the bullets from the player inventory and put them in the slot 0 from the gun and whitout closing inventory a take again that  bullet stack and try to move then to slot 5 from the gun inventory or to any other sloth, the bullestack disappears ad instant or in the next close/open action 

 

if i just single move an item all works like it must but if i move it an then move it again it disappears

 

 

i better i explain again whit this video

 

 

like i say the code is taken from the dispenser class using the tha vainilla gui  but taken the nbt from an item i set in the constructor

well all the calls are done whith the keybind but triggered whith a package in the server side so the call are server side

 

 

package mercenarymod.items.armasdefuego.inventario;

import java.util.ArrayList;
import java.util.Random;

import net.minecraft.block.BlockChest;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ContainerDispenser;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.tileentity.TileEntityLockable;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.IWorldNameable;
import net.minecraft.world.World;

//###################################################################################################
public class inventarioArmas extends TileEntityLockable implements IInventory 
//extends TileEntityDispenser implements IInventory {
{
private ItemStack pistola = null;

private ItemStack[] inventario = new ItemStack[9];

private int SizeInventory = 9;
private int conteodeEtiquetas = 0;
private World worldIn = null;

private static final Random RNG = new Random();

private String customName = "algo"; 

// ###################################################################################################

public inventarioArmas(ItemStack pistola, World worldIn) {
	super();
	this.pistola = pistola;
	this.worldIn = worldIn ;

	NBTTagCompound tagCompund = null;

	if (this.pistola != null) {

	tagCompund = pistola.getTagCompound();

	if (tagCompund != null) {
	readFromNBT(tagCompund);
	}

	}


}
// ###################################################################################################

/**
 * Returns the number of slots in the inventory.
 */
@Override
public int getSizeInventory() // ItemStack pistola
{
	int SizeInventory = 0;

	if (pistola != null) {
		SizeInventory = inventario.length;
	}
	return 9;//SizeInventory;
}

// ###################################################################################################
/**
 * Returns the stack in slot i
 */
@Override
public ItemStack getStackInSlot(int index) // , ItemStack pistola
{

	ItemStack salida = null;

	String s = index +" null ";

	if (this.pistola != null) {

		salida = inventario[index];

		//s ="getStackInSlot("+index+")"+salida.getUnlocalizedName()  ;	
	}


	//System.out.println(s);

	return salida;
}

// ###################################################################################################
/**
 * Removes from an inventory slot (first arg) up to a specified number
 * (second arg) of items and returns them in a new stack.
 */
@Override
public ItemStack decrStackSize(int index, int count) {

	System.out.println("decrStackSize(index="+index+", count"+count+")" );

	ItemStack salida = null;

	if (this.pistola != null) {

		salida = inventario[index];

		int cantidad = salida.stackSize;
		cantidad = cantidad - count;

		salida.stackSize = cantidad;

		if (cantidad < 1) {
			salida = null;
		}



	}

	return salida;

}
// ###################################################################################################
   /**
     * Add the given ItemStack to this Dispenser. Return the Slot the Item was placed in or -1 if no free slot is
     * available.
     */
    public int addItemStack(ItemStack stack)
    {
        for (int i = 0; i < inventario.length; ++i)
        {
            if (inventario[i] == null || inventario[i].getItem() == null)
            {
                this.setInventorySlotContents(i, stack);
                return i;
            }
        }

        return -1;
    }


// ###################################################################################################
/**
 * When some containers are closed they call this on each slot, then drop
 * whatever it returns as an EntityItem - like when you close a workbench
 * GUI.
 */
@Override
public ItemStack getStackInSlotOnClosing(int index) {

	ItemStack salida = null;

	if (this.pistola != null) {
		NBTTagCompound tagCompund = pistola.getTagCompound();

		salida = inventario[index];

	}

	return salida;

}

//###################################################################################################

/**
 * Sets the given item stack to the specified slot in the inventory (can be
 * crafting or armor sections).
 */
@Override
public void setInventorySlotContents(int index, ItemStack stack)
{

	inventario[index] = stack;

}

//###################################################################################################	
/**
 * Returns the maximum stack size for a inventory slot. Seems to always be
 * 64, possibly will be extended. *Isn't this more of a set than a get?*
 */
@Override
public int getInventoryStackLimit(){
	return 64;
}

//###################################################################################################
    /**
     * For tile entities, ensures the chunk containing the tile entity is saved to disk later - the game won't think it
     * hasn't changed and skip it.
     */

    public void markDirty()
    {
        if (worldIn != null)
        {
  
        	
        	writeToNBT(getthisCompound());
/*ñaaa  do nithing */
        	
        	
        }
    }


//###################################################################################################
/**
 * Do not make give this method the name canInteractWith because it clashes
 * with Container
 */
    @Override
public boolean isUseableByPlayer(EntityPlayer player)
{
	return true;
}
    @Override
public void openInventory(EntityPlayer player){
    if (!player.isSpectator())
    {
    	/*ñaaa  do nithing */
    	
    }
}

    @Override
    public void closeInventory(EntityPlayer player)
    {
        if (!player.isSpectator() )
        {
           
        	/*ñaaa  do nothing to */
        	
        }
    }

//###################################################################################################
/**
 * Returns true if automation is allowed to insert the given stack (ignoring
 * stack size) into the given slot.
 */
    @Override
public boolean isItemValidForSlot(int index, ItemStack stack)
{

	return true;


}

    @Override
    public int getField(int id)
    {
        return 0;
    }

    @Override
    public void setField(int id, int value) {}

    @Override
    public int getFieldCount()
    {
        return 0;
    }

    
    @Override
    public void clear()
    {
        for (int i = 0; i < inventario.length; ++i)
        {
        	inventario[i] = null;
        }
        
        System.out.println("$$$ clear()");
        
    }


    @Override
   public String getName()
    {
        return this.customName;
    }

    /**
     * Returns true if this thing is named
     */
    @Override
    public boolean hasCustomName()
    {
        return true;
    }

    //@Override
    public void setCustomName(String name)
    {
        this.customName = name;
    }


@Override
public IChatComponent getDisplayName() {




	IChatComponent displayname = new ChatComponentText(EnumChatFormatting.RED +""+ pistola.getUnlocalizedName()+" sn:/"+getInttag(pistola, "numerodeserie") );



	return displayname;
}

//###################################################################################################
public NBTTagCompound getthisCompound(){
    
	NBTTagCompound compound = new NBTTagCompound();

    NBTTagList nbttaglist = new NBTTagList();

    for (int i = 0; i < inventario.length; ++i)
    {
        if (inventario[i] != null)
        {
            NBTTagCompound nbttagcompound1 = new NBTTagCompound();
            nbttagcompound1.setByte("Slot", (byte)i);
            inventario[i].writeToNBT(nbttagcompound1);
            nbttaglist.appendTag(nbttagcompound1);
        }
    }

    compound.setTag("Inventory", nbttaglist);

  //  this.pistola.setTagCompound(compound);
    
    if (this.hasCustomName())
    {
        compound.setString("CustomName", this.customName);
    }


return compound;

}
// #########################################################################3
@Override
    public void readFromNBT(NBTTagCompound compound)
    {
        //super.readFromNBT(compound);
        NBTTagList nbttaglist = compound.getTagList("Inventory", 10);
        
        
        inventario = new ItemStack[this.getSizeInventory()];

        for (int i = 0; i < nbttaglist.tagCount(); ++i)
        {
            NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i);
            int j = nbttagcompound1.getByte("Slot") & 255;

            
            System.out.println("\n### read from nbt");
            if (j >= 0 && j < inventario.length)
            {
                inventario[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1);
                
                System.out.println("slot ="+i);
                
                if (inventario[j] != null)
                {
                	System.out.println(" "+inventario[j].getUnlocalizedName() );	
                }
                
                System.out.println("###\n");
                
            }
        }

        if (compound.hasKey("CustomName", )
        {
            this.customName = compound.getString("CustomName");
        }
    }

    
// #########################################################################3
@Override
    public void writeToNBT(NBTTagCompound compound)
    {
       // super.writeToNBT(compound);
        
        NBTTagList nbttaglist = new NBTTagList();

        
        System.out.println("\n### write to nbt");
        for (int i = 0; i < inventario.length; ++i)
        {
            if (inventario[i] != null)
            {
             	
                NBTTagCompound nbttagcompound1 = new NBTTagCompound();
                nbttagcompound1.setByte("Slot", (byte)i);
                inventario[i].writeToNBT(nbttagcompound1);
                nbttaglist.appendTag(nbttagcompound1);

                System.out.println("slot"+i+" ="+inventario[i].getUnlocalizedName() );
            }
        }
        System.out.println("### \n");
        compound.setTag("Inventory", nbttaglist);

        
        NBTTagCompound pistolaIn = this.pistola.getTagCompound();
        pistolaIn.setTag("Inventory", nbttaglist);
        
        
        this.pistola.setTagCompound(pistolaIn);
        
        if (this.hasCustomName())
        {
            compound.setString("CustomName", this.customName);
        }
    }

    
    
   // #########################################################################3

    public int getDispenseSlot()
    {
        int i = -1;
        int j = 1;

        for (int k = 0; k < inventario.length; ++k)
        {
            if (inventario[k] != null && RNG.nextInt(j++) == 0)
            {
                i = k;
            }
        }

        return i;
    }



    // #########################################################################3

    public String getGuiID()
    {
        return "minecraft:dispenser";
    }

    public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn)
    {
        return new ContainerDispenser(playerInventory, this);
    }





// #########################################################################3

public static float getFloattag(ItemStack item, String tag) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
		item.setTagCompound(etiquetas);
		return 999.9F;
	}

	float ex = etiquetas.getFloat(tag);
	return ex;

}

// #########################################################################3

public static void setFloattag(ItemStack item, String tag, float value) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
	}

	etiquetas.setFloat(tag, value);
	item.setTagCompound(etiquetas);

}

// #########################################################################3

public static int getInttag(ItemStack item, String tag) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
		item.setTagCompound(etiquetas);
		return 0;
	}

	int ex = etiquetas.getInteger(tag);
	return ex;

}

// #########################################################################3

public static void setInttag(ItemStack item, String tag, int value) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
	}

	etiquetas.setInteger(tag, value);
	item.setTagCompound(etiquetas);

}
// #########################################################################3

public static int[] getIntArraytag(ItemStack item, String tag) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
		item.setTagCompound(etiquetas);
		int[] empty = { 0 };
		return empty;
	}

	int[] ex = etiquetas.getIntArray(tag);
	return ex;

}
// #########################################################################3

public static void setIntArraytag(ItemStack item, String tag, int[] value) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
	}

	etiquetas.setIntArray(tag, value);
	item.setTagCompound(etiquetas);

}

// #########################################################################3

public static Boolean getBooleantag(ItemStack item, String tag) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = new NBTTagCompound();
		item.setTagCompound(etiquetas);
		return false;
	}

	boolean ex = etiquetas.getBoolean(tag);

	return ex;

}

// #########################################################################3

public static void setBooleantag(ItemStack item, String tag, boolean value) {

	NBTTagCompound etiquetas = item.getTagCompound();
	if (etiquetas == null) {
		etiquetas = item.getTagCompound();
	}

	etiquetas.setBoolean(tag, value);
	item.setTagCompound(etiquetas);

}

// #########################################################################3

}

 

 

code in the server side trigered by the package send from the keybind

	if (mensaje.equals("menu00")) {
		inventario(playerIn, mensaje, stack0);
	}

}

static void inventario(EntityPlayer playerIn, String mensaje, ItemStack pistola) {

	if (mensaje.equals("menu00")) {

		System.out.println("mensage recivido menu");

		World worldIn = playerIn.worldObj;

		System.out.println("mundo = " + worldIn.isRemote);

		if (pistola != null){ 
		int ownerId = getInttag(pistola, "ownerId");
		}

		if (!worldIn.isRemote & playerIn instanceof EntityPlayer) {

			System.out.println("###1");


			int playerId = playerIn.getEntityId();

			float distancia = 5.0F;
			double eax = playerIn.posX;
			double eay = (playerIn.posY + playerIn.getEyeHeight());
			double eaz = playerIn.posZ;

			double rotacionYaw = ((playerIn.rotationYaw / 180.0F) * 3.1415926); // rotacion
																				// Horizontal
																				// en
																				// radianes
			double rotacionPitch = ((playerIn.rotationPitch / 180.0F) * 3.1415926); // rotacion
																					// Vertical
																					// en
																					// radianes

			if (rotacionYaw < 0) {
				rotacionYaw = (2 * 6.2831852) + rotacionYaw;
			}

			rotacionYaw = rotacionYaw - 1.5707963; // correccion de -90
													// grados

			if (rotacionYaw < 0) {
				rotacionYaw = (2 * 6.2831852) + rotacionYaw;
			}

			// System.out.println("rotacionPitch ="+ (rotacionPitch) );
			// System.out.println("rotacionYawn ="+ (rotacionYaw) );

			double nposX = eax - (double) (Math.cos(rotacionYaw)) * (Math.cos(rotacionPitch) * distancia);
			double nposY = eay - (Math.sin(rotacionPitch) * distancia);// 0.10000000149011612D
																		// +
			double nposZ = eaz - (double) (Math.sin(rotacionYaw)) * (Math.cos(rotacionPitch) * distancia);

			Vec3 vec31 = new Vec3(eax, eay, eaz);
			Vec3 vec3 = new Vec3(nposX, nposY, nposZ);

			System.out.println("###2 " + vec3);

			System.out.println("motion	" + (nposX - eax) + " , " + (nposY - eay) + " , " + (nposZ - eaz));

			System.out.println("0");
			MovingObjectPosition movingobjectposition = worldIn.rayTraceBlocks(vec31, vec3, false, true, false);

			System.out.println("1");
			vec31 = new Vec3(eax, eay, eaz);
			vec3 = new Vec3(nposX, nposY, nposZ);

			if (movingobjectposition != null) {
				vec3 = new Vec3(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);

				System.out.println("hitvector=" + vec3);
				System.out.println("Blocke=" + worldIn.getBlockState(new BlockPos(vec3)).getBlock().getUnlocalizedName());

			}
			System.out.println("2");

			// ### Aqui estoy modificando para obtener la segunda entidad
			Entity entity = null;

			ArrayList<Entity> entidades = new ArrayList<Entity>();
			entidades.clear();

			List list = worldIn.getEntitiesWithinAABBExcludingEntity(playerIn, playerIn.getEntityBoundingBox().addCoord(nposX - eax, nposY - eay, nposZ - eaz).expand(1.0D, 1.0D, 1.0D));
			double d0 = 0.0D;
			ArrayList<Double> distancias = new ArrayList<Double>();

			distancias.clear();

			int i;
			float f1;

			// only if (!world is remote)
			// if (!this.worldObj.isRemote)
			{

				for (i = 0; i < list.size(); ++i) {
					Entity entity1 = (Entity) list.get(i);

					if (entity1.canBeCollidedWith() && (entity1.getEntityId() != playerId)) {

						f1 = 0.3F;
						AxisAlignedBB axisalignedbb1 = entity1.getEntityBoundingBox().expand((double) f1, (double) f1, (double) f1);
						MovingObjectPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vec31, vec3);

						if (movingobjectposition1 != null) {
							double d1 = vec31.distanceTo(movingobjectposition1.hitVec);

							if (entity1 != null) {

								entidades.add(entity1);
								distancias.add(d1);

							}

							if ((d1 < d0 || d0 == 0.0D)) {
								entity = entity1;
								d0 = d1;

							}
						}
					}
				}

			} // only if (!world is remote)

			boolean abrirMenuPropio = false;

			if (entity != null) {

				EntityLivingBase entity2 = null;

				if (entity instanceof EntityLivingBase) {
					entity2 = (EntityLivingBase) entity;
					System.out.println("entity2 = " + entity2.getName());
				} else {
					abrirMenuPropio = true;
				}

				ItemStack gun = entity2.getHeldItem();

				if (gun != null) {

					boolean isCompatibleGun = armasDisparables.esDisparable(gun);

					if (isCompatibleGun) {

						NBTTagCompound compound = gun.getTagCompound();

						if (compound != null) {

							mercenarymod.items.armasdefuego.inventario.inventarioArmas invPistola = new mercenarymod.items.armasdefuego.inventario.inventarioArmas(gun, worldIn);

							invPistola.setCustomName("Entity whith Pistola");

							((EntityPlayer) playerIn).displayGUIChest(invPistola);// (TileEntityDispenser)


						}

					}

				} else {
					abrirMenuPropio = true;
				}

			} else {
				abrirMenuPropio = true;
			}



			if (abrirMenuPropio) {

				if (pistola == null)
				{
					abrirMenuPropio = false;
				}
			}


			if (abrirMenuPropio) {

				ItemStack gun = playerIn.getHeldItem();

				boolean isCompatibleGun = armasDisparables.esDisparable(gun);

				if (isCompatibleGun) {

					NBTTagCompound compound = pistola.getTagCompound();

					if (compound != null) {

						mercenarymod.items.armasdefuego.inventario.inventarioArmas invPistola = new mercenarymod.items.armasdefuego.inventario.inventarioArmas(pistola, worldIn);

						invPistola.setCustomName("playerIn Pistola");

						((EntityPlayer) playerIn).displayGUIChest(invPistola);// (TileEntityDispenser)
setBooleantag(pistola, "menu00", false);
					}

				}

			}

			// get the gun from the entity

			// setInttag(pistola, "ownerId", playerIn.getEntityId());

		}

	}

}

// #########################################################################3

 

 

 

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Hi, I want to make a client-only mod, everything is ok, but when I use shaders, none of the textures rendered in RenderLevelStageEvent nor the crow entity model are rendered, I want them to be visible, because it's a horror themed mod Here is how i render the crow model in the CrowEntityRenderer<CrowEntity>, by the time i use this method, i know is not the right method but i don't think this is the cause of the problem, the renderType i'm using is entityCutout @Override public void render(CrowEntity p_entity, float entityYaw, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource, int packedLight) { super.render(p_entity, entityYaw, partialTick, poseStack, bufferSource, packedLight); ClientEventHandler.getClient().crow.renderToBuffer(poseStack, bufferSource.getBuffer(ClientEventHandler.getClient().crow .renderType(TEXTURE)), packedLight, OverlayTexture.NO_OVERLAY, Utils.rgb(255, 255, 255)); } Here renderLevelStage @Override public void renderWorld(RenderLevelStageEvent e) { horrorEvents.draw(e); } Here is how i render every event public void draw(RenderLevelStageEvent e) { for (HorrorEvent event : currentHorrorEvents) { event.tick(e.getPartialTick()); event.draw(e); } } Here is how i render the crow model on the event @Override public void draw(RenderLevelStageEvent e) { if(e.getStage() == RenderLevelStageEvent.Stage.AFTER_ENTITIES) { float arcProgress = getArcProgress(0.25f); int alpha = (int) Mth.lerp(arcProgress, 0, 255); int packedLight = LevelRenderer.getLightColor(Minecraft.getInstance().level, blockPos); VertexConsumer builder = ClientEventHandler.bufferSource.getBuffer(crow); Crow<CreepyBirdHorrorEvent> model = ClientEventHandler .getClient().crow; model.setupAnim(this); RenderHelper.renderModelInWorld(model, position, offset, e.getCamera(), e.getPoseStack(), builder, packedLight, OverlayTexture.NO_OVERLAY, alpha); builder = ClientEventHandler.bufferSource.getBuffer(eyes); RenderHelper.renderModelInWorld(model, position, offset, e.getCamera(), e.getPoseStack(), builder, 15728880, OverlayTexture.NO_OVERLAY, alpha); } } How i render the model public static void renderModelInWorld(Model model, Vector3f pos, Vector3f offset, Camera camera, PoseStack matrix, VertexConsumer builder, int light, int overlay, int alpha) { matrix.pushPose(); Vec3 cameraPos = camera.getPosition(); double finalX = pos.x - cameraPos.x + offset.x; double finalY = pos.y - cameraPos.y + offset.y; double finalZ = pos.z - cameraPos.z + offset.z; matrix.pushPose(); matrix.translate(finalX, finalY, finalZ); matrix.mulPose(Axis.XP.rotationDegrees(180f)); model.renderToBuffer(matrix, builder, light, overlay, Utils .rgba(255, 255, 255, alpha)); matrix.popPose(); matrix.popPose(); } Thanks in advance
    • Here's the link: https://mclo.gs/7L5FibL Here's the link: https://mclo.gs/7L5FibL
    • Also the mod "Connector Extras" modifies Reach-entity-attributes and can cause fatal errors when combined with ValkrienSkies mod. Disable this mod and continue to use Syntra without it.
    • Hi everyone. I was trying modify the vanilla loot of the "short_grass" block, I would like it drops seeds and vegetal fiber (new item of my mod), but I don't found any guide or tutorial on internet. Somebody can help me?
    • On 1.20.1 use ValkrienSkies mod version 2.3.0 Beta 1. I had the same issues as you and it turns out the newer beta versions have tons of unresolved incompatibilities. If you change the version you will not be required to change the versions of eureka or any other additions unless prompted at startup. This will resolve Reach-entity-attributes error sound related error and cowardly errors.
  • Topics

×
×
  • Create New...

Important Information

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