Jump to content

Capability shares the world


LuccaPossamai

Recommended Posts

I've created a container that stores items for each player, it acts more like and EnderChest. And, to make this I use Capabilities, but when I was testing in a world, I see that the container share items with other worlds. For example, in the world "BananaBoys" I store 2 apples and 1 diamond axe, and when I enter in other world like "BananaGirls", in the container have 2 apples and 1 diamond axe. Someone know how to make the container unique for each world?

Edited by LuccaPossamai
Link to comment
Share on other sites

Capability.IStorage:

Spoiler

package com.lucca.mohard.block.altar.capability;

import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.NonNullList;
import net.minecraftforge.common.capabilities.Capability;

public class InventoryStorage implements Capability.IStorage<AltarCapability> {


    @Override
    public INBT writeNBT(Capability<AltarCapability> capability, AltarCapability instance, Direction side){
        ListNBT listnbt = new ListNBT();

        for(int i = 0; i < 9; ++i) {
            ItemStack itemstack = instance.getStackInSlot(i);
            if (!itemstack.isEmpty()) {
                CompoundNBT compoundnbt = new CompoundNBT();
                compoundnbt.putByte("SlotAltar", (byte)i);
                itemstack.save(compoundnbt);
                listnbt.add(compoundnbt);
            }
        }

        return listnbt;
    }

    @Override
    public void readNBT(Capability<AltarCapability> capability, AltarCapability instance, Direction side, INBT nbt) {
        if(nbt instanceof ListNBT) {
            ListNBT p_70486_1_ = (ListNBT) nbt;

            for(int i = 0; i < 9; ++i) {
                instance.insertItem(i, ItemStack.EMPTY, false);
            }

            for(int k = 0; k < p_70486_1_.size(); ++k) {
                CompoundNBT compoundnbt = p_70486_1_.getCompound(k);
                int j = compoundnbt.getByte("SlotAltar") & 255;
                if (j >= 0 && j < 9) {
                    instance.insertItem(j, ItemStack.of(compoundnbt), false);
                }
            }
        }

    }


    public static NonNullList<ItemStack> convertNBTtoItems(Capability<AltarCapability> capability, AltarCapability instance, Direction side, INBT nbt) {
        NonNullList<ItemStack> items = NonNullList.withSize(9, ItemStack.EMPTY);
        if(nbt instanceof ListNBT) {
            ListNBT p_70486_1_ = (ListNBT) nbt;

            for(int i = 0; i < 9; ++i) {
                instance.insertItem(i, ItemStack.EMPTY, false);
            }

            for(int k = 0; k < p_70486_1_.size(); ++k) {
                CompoundNBT compoundnbt = p_70486_1_.getCompound(k);
                int j = compoundnbt.getByte("SlotAltar") & 255;
                if (j >= 0 && j < 9) {
                    items.set(k, ItemStack.of(compoundnbt));
                }
            }
        }
        return items;
    }
}

 

The class that extends the capability:

Spoiler

package com.lucca.mohard.block.altar.capability;

import com.lucca.mohard.ExampleMod;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;

import javax.annotation.Nonnull;

public class AltarCapabilityDef implements AltarCapability {

    private static NonNullList<ItemStack> items = NonNullList.withSize(9, ItemStack.EMPTY);

    @CapabilityInject(AltarCapability.class)
    public static final Capability<AltarCapability> ALTAR_INVENTORY = null;

    public static final ResourceLocation ID = new ResourceLocation(ExampleMod.MOD_ID, "altar_inventory");

    @Override
    public int getSlots() {
        return items.size();
    }

    @Nonnull
    @Override
    public ItemStack getStackInSlot(int slot) {
        return items.get(slot);
    }

    @Nonnull
    @Override
    public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {
        if(simulate){
            try{
                return items.set(slot, stack);
            } catch (Exception ex){
                System.out.println("Error in insertItem simulation");
                return items.get(slot);
            }
        } else {
            return items.set(slot, stack);
        }
    }

    @Nonnull
    @Override
    public ItemStack extractItem(int slot, int amount, boolean simulate) {
        if(simulate){
            try{
                items.get(slot).setCount(items.get(slot).getCount() - amount);
                return items.get(slot);
            } catch (Exception ex){
                System.out.println("Error in extractItem simulation");
                return items.get(slot);
            }
        } else {
            items.get(slot).setCount(items.get(slot).getCount() - amount);
            return items.get(slot);
        }
    }

    @Override
    public int getSlotLimit(int slot) {
        return 9;
    }

    @Override
    public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
        return true;
    }

    public static void setItems(NonNullList<ItemStack> itemsList){
        items = itemsList;
    }

    public static NonNullList<ItemStack> getItems(){
        return items;
    }

}

 

The ICapabilitySerializable:

Spoiler

package com.lucca.mohard.block.altar.capability;

import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class AltarSerializable implements ICapabilitySerializable {


    private static final LazyOptional<AltarCapabilityDef> holder = LazyOptional.of(AltarCapabilityDef :: new);
    private static final AltarCapability altarCapability = new AltarCapabilityDef();

    public boolean hasCapability( Capability< ? > capability) {

        if ( capability == AltarCapabilityDef.ALTAR_INVENTORY ) {

            return true ;

        }

        return false ;
    }

    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if(cap.equals(AltarCapabilityDef.ALTAR_INVENTORY)){
            return holder.cast();
        }
        return null;
    }


    @Override
    public INBT serializeNBT() {
        if(AltarCapabilityDef.ALTAR_INVENTORY == null){
            return new CompoundNBT();
        }
        return AltarCapabilityDef.ALTAR_INVENTORY.writeNBT(altarCapability, null);
    }

    @Override
    public void deserializeNBT(INBT nbt) {
        if(AltarCapabilityDef.ALTAR_INVENTORY != null){
            if(nbt == null ){
                nbt = new CompoundNBT();
            }
            AltarCapabilityDef.ALTAR_INVENTORY.readNBT(altarCapability, null, nbt);
        }
    }


}

 

And the container Inventory:

Spoiler

package com.lucca.mohard.block.altar.capability;

import com.lucca.mohard.block.altar.AltarTileEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.util.NonNullList;
import net.minecraftforge.event.entity.player.PlayerContainerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class AltarInventory extends Inventory {

    private AltarTileEntity ALTAR;

    public AltarInventory(PlayerEntity jogador) {
        super(9);
        setItems(jogador);
    }

    public void setItems(PlayerEntity jogador){
        if(jogador.getCapability(AltarCapabilityDef.ALTAR_INVENTORY) == null){
            for (int i = 0; i < 9; i++) {
                this.setItem(i, ItemStack.EMPTY);
            }
        } else {
            INBT tag = new InventoryStorage().writeNBT(AltarCapabilityDef.ALTAR_INVENTORY,
                    AltarCapabilityDef.ALTAR_INVENTORY.getDefaultInstance(),
                    null);
            AltarCapabilityDef.setItems(InventoryStorage.convertNBTtoItems(AltarCapabilityDef.ALTAR_INVENTORY,
                    AltarCapabilityDef.ALTAR_INVENTORY.getDefaultInstance(),
                    null,
                    tag));

            jogador.getCapability(AltarCapabilityDef.ALTAR_INVENTORY).ifPresent(inv -> {
                for (int i = 0; i < 9; i++) {
                    this.setItem(i, inv.getStackInSlot(i));
                }
            });
        }
    }




    public static NonNullList<ItemStack> getItems(PlayerEntity jogador){
        NonNullList<ItemStack> lista = NonNullList.withSize(9, ItemStack.EMPTY);
        if(jogador.getCapability(AltarCapabilityDef.ALTAR_INVENTORY) != null){
            jogador.getCapability(AltarCapabilityDef.ALTAR_INVENTORY).ifPresent(inv -> {
                for (int i = 0; i < 9; i++) {
                    lista.set(i, inv.getStackInSlot(i));
                }
            });
        }
        return lista;
    }


    public void fromTag(ListNBT p_70486_1_) {
        for(int i = 0; i < this.getContainerSize(); ++i) {
            this.setItem(i, ItemStack.EMPTY);
        }

        for(int k = 0; k < p_70486_1_.size(); ++k) {
            CompoundNBT compoundnbt = p_70486_1_.getCompound(k);
            int j = compoundnbt.getByte("SlotAltar") & 255;
            if (j >= 0 && j < this.getContainerSize()) {
                this.setItem(j, ItemStack.of(compoundnbt));
            }
        }

    }

    public ListNBT createTag(NonNullList<ItemStack> list) {
        ListNBT listnbt = new ListNBT();

        for(int i = 0; i < list.size(); ++i) {
            ItemStack itemstack = list.get(i);
            if (!itemstack.isEmpty()) {
                CompoundNBT compoundnbt = new CompoundNBT();
                compoundnbt.putByte("SlotAltar", (byte)i);
                itemstack.save(compoundnbt);
                listnbt.add(compoundnbt);
            }
        }

        return listnbt;
    }


    public void setActiveAltar(AltarTileEntity tileEntity) {
        this.ALTAR = tileEntity;
    }


}

 

 

Link to comment
Share on other sites

22 hours ago, LuccaPossamai said:

if(jogador.getCapability(AltarCapabilityDef.ALTAR_INVENTORY) != null){

it cant be null

 

@Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        if(cap.equals(AltarCapabilityDef.ALTAR_INVENTORY)){
            return holder.cast();
        }
        return null;
    }

dont return null here that will break use LazyOptional.empty()

Link to comment
Share on other sites

1 hour ago, loordgek said:

dont return null here that will break use LazyOptional.empty()

Don't do that either, return super.getCapability()

1 hour ago, loordgek said:

it cant be null

the real problem here is not that it can or can't be null, but that get().orElse(null) is just bad.
If it really should never be null, then get().orElseThrow(new Exception("capability was unexpectedly missing!"))
If it may be null, use get().ifPresent(cap -> { do stuff });

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

11 minutes ago, Draco18s said:

Don't do that either, return super.getCapability()

there is no super

public class AltarSerializable implements ICapabilitySerializable

12 minutes ago, Draco18s said:

the real problem here is not that it can or can't be null, but that get().orElse(null) is just bad.

he returns null in getCapability

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



×
×
  • Create New...

Important Information

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