Jump to content

[1.20.4] way to directly acces the nbt database and manually save or retrive the nbt data for blockEntities ?


Recommended Posts

 

I have problems whit mi blockEntities they just save data only when it feels like 

stonehead.png

I just retake he topic after several weeks i know it not the menu nor the packages system 

was thinking something xtreame like make the block entities to read write the data as .nbt text files just coze i can but think don't worts the effort 

#################

???

mi question is if theres a way to espose and  directly messup whit the minecraft nbt database system ??

like 

SELECT nbt FROM miwarudo WHERE x='127' and y='80' and z='-3627'

or something whit

CompoundTag worldnbt = warudo.getLevelData().something; ??

CompoundTag blockentitynbt = worldnbt.getDataAt(x,y,z) ??

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Link to comment
Share on other sites

I'm struggling to guess what on earth are you trying to achieve, or what do you want cause your post is a lil bit wonky,  but the BlockEntity class has methods like SaveAdditional(CompoundTag) and load(CompoundTag) that should manage serialization and deserialization of your block entity NBT data for most cases and that you can override.

If you mean reading NBT data of things "Inside" your BE, (in a slot) I'm pretty sure you can get an ItemStack out of any slot inside your BE from which to acess NBT data of the item in the slot.

If you need the NBT data of a specific block entity you can call ServerLevel.getBlockEntity()

Blocks don't have NBT data iirc.

It would help to get an explanation on what is that your BE does and whats the current look of your BE class.

Edited by chxr
Typos
Link to comment
Share on other sites

well

The problem is the data in mi blockentity, its not being saved when i close the game

i put items on it i retrive items from it all just seems good, the problem cames until i close minecraft then when i reload the word i have an older version of the items saved or just an empty briefcase

 

normally when you declare an entity or a block entity or an item capability, forge automatically keeps track of changes and save the data in nbt format all of this by itself 
in this moments i have some items whit capabilities, those work right 
i have entities , those also works right 

but all of mi blockentities all of them are storages briefcase and all of them fails, save the data sometimes most of the time don't 

well i have only like 3 blockentities up now 

 

 



 

Link to comment
Share on other sites

I'm sure load and SaveAdditional are what you are looking for, probably. Mind sharing your BE class code?

You also need to override onLoad method if you haven't

Edited by chxr
Link to comment
Share on other sites

Posted (edited)

 hola thanks for answering 

i set some system outs to test and see whats going on 

	    @Override
    protected void saveAdditional( CompoundTag nbt ){
        
        nbt.put("itemhandler", itemhandler.serializeNBT() );
        nbt.putInt("progress", this.progress );
	        System.out.println("saveAdditional(nbt)");        
        System.out.println(NbtUtils.prettyPrint(nbt)); //<-- this is whats getting saved
        super.saveAdditional( nbt );
    }
    @Override
    public void load( CompoundTag nbt ){
	        itemhandler.deserializeNBT( nbt.getCompound("itemhandler") );
        this.progress = nbt.getInt("progress" );
	        System.out.println(NbtUtils.prettyPrint(nbt)); //<-- this is whats minecraft is giving back to the entity 
        System.out.println("load(nbt)");
        super.load( nbt );
    }
	

 

This dead adventurer body  has two parts a block and a block Item  both has their own item-handlers and their own menus all of that seems fine 

Testing remarks :
*when i change some element inside the gui  it triggers the saveAdditional(nbt) system out and shows a pretty print of the data being saved 

*when the world map loads it triggers the load(nbt) system out and shows a pretty print of the data minecraft is giving to this Block Entity

For the testing i gonna set mi BlockEntityBodyBlock, save something in it, close minecraft, fireup the game again and check if the items remain 

 

 

################

first try set the block entity (dead adventurer body like shaped) and left only a weath seed  in the slot 10
the console says its all right 

Spoiler
				
			saveAdditional(nbt)
		{ "itemhandler": {
		    "Items"     : list<TAG_Compound>[3] [
		      { "Count": 1b,
		        "Slot" : 10,
		        "id"   : "minecraft:wheat_seeds"
		      }
		    ],
		    "action"    : 0b,
		    "limit"     : 100s,
		    "start_time": 0L,
		    "time"      : 0s
		  },
		  "progress"   : 0
		}				
			

 

close minecraft, launch it again
i see the system out whit the data returned to the entity and its look good theres is only a weed seed 

Spoiler
				
			    load(nbt)
		{ "id"         : "mercmod:blockentitymobblock",
		  "itemhandler": {
		    "Items"     : list<TAG_Compound>[1] [
		      { "Count": 1b,
		        "Slot" : 10,
		        "id"   : "minecraft:wheat_seeds"
		      }
		    ],
		    "action"    : 0b,
		    "limit"     : 100s,
		    "start_time": 0L,
		    "time"      : 0s
		  },
		  "keepPacked" : 0b,
		  "progress"   : 0,
		  "x"          : -40,
		  "y"          : 72,
		  "z"          : 38
		}				
			

################

Second try,
now i gonna change the seed for two arrows 

the console says its all right the two arrows are being saved 
 

Spoiler
				
			saveAdditional(nbt)
		{ "itemhandler": {
		    "Items"     : list<TAG_Compound>[3] [
		      { "Count": 1b,
		        "Slot" : 9,
		        "id"   : "minecraft:arrow"
		      },
		      { "Count": 1b,
		        "Slot" : 11,
		        "id"   : "minecraft:arrow"
		      }
		    ],
		    "action"    : 0b,
		    "limit"     : 100s,
		    "start_time": 0L,
		    "time"      : 0s
		  },
		  "progress"   : 0
		}				
			

#########

Now close and run again

bam Error  minecraft returns the original data whit only a wheat seed
the two arrows has been loss

Spoiler
				
	load(nbt)
		{ "id"         : "mercmod:blockentitymobblock",
		  "itemhandler": {
		    "Items"     : list<TAG_Compound>[1] [
		      { "Count": 1b,
		        "Slot" : 10,
		        "id"   : "minecraft:wheat_seeds"
		      }
		    ],
		    "action"    : 0b,
		    "limit"     : 100s,
		    "start_time": 0L,
		    "time"      : 0s
		  },

 

 

##########

try again now i gonna put 3 wheat seeds

Console system out says it gets it and is saving the data

Spoiler
				
			saveAdditional(nbt)
		{ "itemhandler": {
		    "Items"     : list<TAG_Compound>[3] [
		      { "Count": 1b,
		        "Slot" : 9,
		        "id"   : "minecraft:wheat_seeds"
		      },
		      { "Count": 1b,
		        "Slot" : 10,
		        "id"   : "minecraft:wheat_seeds"
		      },
		      { "Count": 1b,
		        "Slot" : 11,
		        "id"   : "minecraft:wheat_seeds"
		      }
		    ],
		    "action"    : 0b,
		    "limit"     : 100s,
		    "start_time": 0L,
		    "time"      : 0s
		  },
		  "progress"   : 0
		}				
			

 

##############

but after close fire again 

Spoiler
				
			load(nbt)
		{ "id"         : "mercmod:blockentitymobblock",
		  "itemhandler": {
		    "Items"     : list<TAG_Compound>[1] [
		      { "Count": 1b,
		        "Slot" : 10,
		        "id"   : "minecraft:wheat_seeds"
		      }
		    ],
		    "action"    : 0b,
		    "limit"     : 100s,
		    "start_time": 0L,
		    "time"      : 0s
		  },
		  "keepPacked" : 0b,
		  "progress"   : 0,
		  "x"          : -40,
		  "y"          : 72,
		  "z"          : 38
		}				
			

wheat seed,  data losed once more time  and it just throw the original  

#######################################################################################

sorry for the long post and the crappy video 

this is the reason why i say its saving the Block Entity data only when it feels like 
coze its saves data when it feels like 

¿ its something wrong whit mi BlockEntity.saveAdditional() 

if  i keep trying eventually it updates and the data chages 

 

 

i alredy try to 
level.removeBlockEntity(pos);

level.setBlockEntity(pos, bebb);

 

 

BlockEntityBodyBlock.class

Spoiler

				
			package mercmod.blockentitys;//panel_blockentity				
			import mercmod.capabity.be_handler;
		import mercmod.capabity.briefcase_be_handler;
		import mercmod.menus.MenuBodyBlock;
		import net.minecraft.core.BlockPos;
		import net.minecraft.core.Direction;
		import net.minecraft.nbt.CompoundTag;
		import net.minecraft.nbt.NbtUtils;
		import net.minecraft.network.chat.Component;
		import net.minecraft.world.Containers;
		import net.minecraft.world.MenuProvider;
		import net.minecraft.world.SimpleContainer;
		import net.minecraft.world.entity.player.Inventory;
		import net.minecraft.world.entity.player.Player;
		import net.minecraft.world.inventory.AbstractContainerMenu;
		import net.minecraft.world.inventory.ContainerData;
		import net.minecraft.world.item.Item;
		import net.minecraft.world.level.Level;
		import net.minecraft.world.level.block.entity.BlockEntity;
		import net.minecraft.world.level.block.state.BlockState;
		import net.minecraftforge.common.capabilities.Capability;
		import net.minecraftforge.common.capabilities.ForgeCapabilities;
		import net.minecraftforge.common.util.LazyOptional;
		import net.minecraftforge.items.IItemHandler;
		import net.minecraftforge.items.ItemStackHandler;
		import org.jetbrains.annotations.NotNull;
		import org.jetbrains.annotations.Nullable;				
			public class BlockEntityBodyBlock extends BlockEntity implements MenuProvider
		{
		    //https://youtu.be/uV81DhuZ96w?t=687				
			    protected final ContainerData data;
		    private int progress = 0;
		    private int maxprogress = 70;				
			    private static final int INPUT_SLOT = 0;
		    private static final int OUTPUT_SLOT = 1;				
			    public BlockEntityBodyBlock(BlockPos pos, BlockState blkstate) {
		        super(BlockEntityInit.BLOCKENTITYMOBBLOCK.get() , pos, blkstate);
		        this.data = new ContainerData() {
		            @Override
		            public int get(int pindex) {
		                return switch(pindex){
		                    case 0 -> BlockEntityBodyBlock.this.progress;
		                    case 1 -> BlockEntityBodyBlock.this.maxprogress;
		                    default -> 0;
		                };
		            }				
			            @Override
		            public void set(int pindex, int pvalue) {
		                switch(pindex) {
		                    case 0 -> BlockEntityBodyBlock.this.progress = pvalue;
		                    case 1 -> BlockEntityBodyBlock.this.maxprogress = pvalue;
		                }
		            }				
			            @Override
		            public int getCount() {
		                return 2;
		            }
		        };
		    }				
			    @Override
		    public Component getDisplayName() {
		        return Component.literal("Dead Body Block");
		    }				
			    @Nullable
		    @Override
		    public AbstractContainerMenu createMenu(int id, Inventory inventory, Player pe) {
		        //System.out.println("#BlockEntityClass createMenu");
		        return new MenuBodyBlock(id, inventory,this, this.data);
		    }				
			    private LazyOptional<IItemHandler> lazyitemhandler = LazyOptional.empty();				
			    //private final ItemStackHandler itemhandler = new ItemStackHandler(14);
		    private final be_handler itemhandler = new be_handler(this, 14);				
			    @Override
		    public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side){
		        if(cap == ForgeCapabilities.ITEM_HANDLER){
		            return lazyitemhandler.cast();
		        }
		        return super.getCapability(cap, side);
		    }				
			    @Override
		    public void onLoad(){
		    super.onLoad();
		    lazyitemhandler = LazyOptional.of(() -> itemhandler);
		    }				
			    @Override
		    public void invalidateCaps(){
		        super.invalidateCaps();
		        lazyitemhandler.invalidate();
		    }				
			    public void drops(){
		        SimpleContainer inventory = new SimpleContainer( itemhandler.getSlots() );
		        for(int index = 0 ; index < itemhandler.getSlots() ; index ++){
		            inventory.setItem(index, itemhandler.getStackInSlot(index));
		        }
		        Containers.dropContents(this.level, this.worldPosition, inventory);
		    }				
			@Override
		    protected void saveAdditional( CompoundTag nbt ){				
			        nbt.put("itemhandler", itemhandler.serializeNBT() );
		        nbt.putInt("progress", this.progress );				
			        System.out.println("saveAdditional(nbt)");
		        System.out.println(NbtUtils.prettyPrint(nbt));
		        super.saveAdditional( nbt );
		    }
		    @Override
		    public void load( CompoundTag nbt ){				
			        itemhandler.deserializeNBT( nbt.getCompound("itemhandler") );
		        this.progress = nbt.getInt("progress" );				
			        System.out.println("load(nbt)");
		        System.out.println(NbtUtils.prettyPrint(nbt));
		        super.load( nbt );
		    }				
			    //@Override
		    public void tick(Level pLevel, BlockPos pPos, BlockState pState) {
		    }				
			    private boolean canInsertItemIntoOutputSlot(Item item) {
		        return this.itemhandler.getStackInSlot(OUTPUT_SLOT).isEmpty() || this.itemhandler.getStackInSlot(OUTPUT_SLOT).is(item);
		    }				
			    private boolean canInsertAmountIntoOutputSlot(int count) {
		        return this.itemhandler.getStackInSlot(OUTPUT_SLOT).getCount() + count <= this.itemhandler.getStackInSlot(OUTPUT_SLOT).getMaxStackSize();
		    }
		}				
			 				
			

 

BlockEntityInit.class

Spoiler

				
			package mercmod.blockentitys;
		import mercmod.blocks.BlockInit;
		import mercmod.mercmod;
		import net.minecraft.Util;
		import net.minecraft.resources.ResourceLocation;
		import net.minecraft.util.datafix.fixes.References;
		import net.minecraft.world.level.block.entity.BlockEntity;
		import net.minecraft.world.level.block.entity.BlockEntityType;
		import net.minecraftforge.eventbus.api.IEventBus;
		import net.minecraftforge.registries.DeferredRegister;
		import net.minecraftforge.registries.ForgeRegistries;
		import net.minecraftforge.registries.RegistryObject;				
			import java.util.function.BiConsumer;
		import com.mojang.datafixers.types.Type;
		public class BlockEntityInit {
		    public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITIES =
		            DeferredRegister.create(ForgeRegistries.BLOCK_ENTITY_TYPES, mercmod.MOD_ID);				
			public static final RegistryObject<BlockEntityType<Panel_BlockEntity>> PANEL_BLOCKENTITY =
		        BLOCK_ENTITIES.register( "panel_blockentity", () ->
		                BlockEntityType.Builder.of( Panel_BlockEntity::new,
		                        BlockInit.OAK_LADDER.get() ).build(null)  );				
			    public static final RegistryObject<BlockEntityType<BlockEntityBriefcase>> BLOCKENTITYBRIEFCASE =
		            BLOCK_ENTITIES.register( "blockentitybriefcase", () ->
		                    BlockEntityType.Builder.of( BlockEntityBriefcase::new,
		                            BlockInit.BRIEFCASE.get() ).build(null)  );				
			
		    public static final RegistryObject<BlockEntityType<BlockEntityHardcase>> BLOCKENTITYHARDCASE =
		            BLOCK_ENTITIES.register( "blockentityhardcase", () ->
		                    BlockEntityType.Builder.of( BlockEntityHardcase::new,
		                            BlockInit.HARDCASE.get() ).build( null) );				
			    public static final RegistryObject<BlockEntityType<BlockEntityBodyBlock>> BLOCKENTITYMOBBLOCK =
		            BLOCK_ENTITIES.register( "blockentitymobblock", () ->
		                    BlockEntityType.Builder.of( BlockEntityBodyBlock::new,
		                            BlockInit.DEAD_BODY.get() ).build( null ) );				
			    public static void register(IEventBus eventBus) {
		        BLOCK_ENTITIES.register(eventBus);
		    }				
			}				
			

 

 

body_blockitem.class

Spoiler

				
			package mercmod.blockitems;				
			import mercmod.blockentitys.BlockEntityBodyBlock;
		import mercmod.capabity.bi_c_provider;
		import mercmod.capabity.bi_handler;
		import mercmod.menus.MenuBodyBlockItem;
		import net.minecraft.core.BlockPos;
		import net.minecraft.nbt.CompoundTag;
		import net.minecraft.nbt.NbtUtils;
		import net.minecraft.network.chat.Component;
		import net.minecraft.world.InteractionHand;
		import net.minecraft.world.InteractionResult;
		import net.minecraft.world.InteractionResultHolder;
		import net.minecraft.world.MenuProvider;
		import net.minecraft.world.entity.LivingEntity;
		import net.minecraft.world.entity.player.Inventory;
		import net.minecraft.world.entity.player.Player;
		import net.minecraft.world.inventory.AbstractContainerMenu;
		import net.minecraft.world.item.BlockItem;
		import net.minecraft.world.item.ItemStack;
		import net.minecraft.world.item.context.BlockPlaceContext;
		import net.minecraft.world.item.context.UseOnContext;
		import net.minecraft.world.level.ClipContext;
		import net.minecraft.world.level.Level;
		import net.minecraft.world.level.block.Block;
		import net.minecraft.world.level.block.entity.BlockEntity;
		import net.minecraft.world.level.block.state.BlockState;
		import net.minecraft.world.phys.BlockHitResult;
		import net.minecraft.world.phys.HitResult;
		import net.minecraft.world.phys.Vec3;
		import net.minecraftforge.common.capabilities.ForgeCapabilities;
		import net.minecraftforge.common.capabilities.ICapabilityProvider;
		import net.minecraftforge.common.extensions.IForgeServerPlayer;
		import org.jetbrains.annotations.NotNull;
		import org.jetbrains.annotations.Nullable;				
			public class body_blockitem extends BlockItem implements MenuProvider {
		   public static final String BLOCK_ENTITY_TAG = "BlockEntityTag";
		   public static final String BLOCK_STATE_TAG = "BlockStateTag";
		   /** @deprecated */
		   @Deprecated
		   private final Block block;				
			   public body_blockitem(Block blk, Properties properties) {
		      super(blk, properties);
		      this.block = blk;
		   }				
			   // ########## ########## ########## ##########
		   @Override
		   public @NotNull Component getDisplayName()
		   {
		      return Component.literal("Body as Item");
		   }				
			   // ########## ########## ########## ##########
		   public int getContainerSize() {
		      return 14;
		   }				
			   // ########## ########## ########## ##########				
			   public static CompoundTag get_nbt(ItemStack container){
		      CompoundTag nbt = ( container.hasTag() )? container.getTag() : new CompoundTag() ;
		      if(!nbt.contains("time")) {
		         nbt.putLong("tick", 0L);
		      }
		      return nbt;
		   }				
			   // ########## ########## ########## ##########
		   public static boolean can_do_it(ItemStack container){
		      // System.out.print("can_do_it("  );				
			      CompoundTag nbt = get_nbt(container);
		      long millis = System.currentTimeMillis();				
			      if( ( millis - nbt.getLong("time" ) ) > 1000 ){ //only once every second
		         nbt.putLong("time", millis );
		         container.setTag(nbt);
		         //System.out.println("true);"  );
		         return true;
		      }
		      // System.out.println("false);"  );
		      return false;
		   }				
			   // ########## ########## ########## ##########
		   @Nullable
		   @Override
		   public ICapabilityProvider initCapabilities(ItemStack container, @Nullable CompoundTag nbt)
		   {
		      return new bi_c_provider(container, 14);
		   }				
			   // ########## ########## ########## ##########
		   public static bi_handler get_itemhandler(ItemStack helditem) {
		      //bi_handler bh = get_itemhandler(helditem);				
			      bi_handler bh = ((bi_handler) helditem.getCapability(ForgeCapabilities.ITEM_HANDLER)
		              .orElseThrow(() -> new RuntimeException("O_O")));
		      return bh;
		   }				
			   // ########## ########## ########## ##########
		   @Nullable
		   @Override
		   public AbstractContainerMenu createMenu(int containerId, @NotNull Inventory inventory, @NotNull Player player)
		   {
		      return new MenuBodyBlockItem( containerId, inventory   );
		   }				
			   // ########## ########## ########## ##########
		   //override normal block set process
		   @Override
		   public InteractionResult useOn(UseOnContext p_40581_) {
		      return InteractionResult.PASS;
		   }				
			
		   // ########## ########## ########## ##########
		   @Override
		   public InteractionResultHolder<ItemStack> use(Level warudo, Player pe, InteractionHand hand) {
		      //System.out.println("use()");
		      ItemStack helditem = pe.getItemInHand(hand);
		      if(can_do_it(helditem)){
		         if( !warudo.isClientSide() ) {
		            if (!pe.isCrouching()) {
		               open_briefcase(warudo, pe, helditem);//<---
		            }
		            if (pe.isCrouching()) {
		               set_as_block(warudo, pe, hand, helditem);//<---
		            }
		         }
		      }
		      return InteractionResultHolder.success(helditem);
		   }				
			   // ########## ########## ########## ##########
		   public void open_briefcase(Level warudo, Player pe, ItemStack helditem){
		      if (helditem.getCapability(ForgeCapabilities.ITEM_HANDLER).isPresent()) {
		         bi_handler bh = get_itemhandler(helditem);				
			         IForgeServerPlayer ifpe = (IForgeServerPlayer) pe;
		         ifpe.openMenu((MenuProvider) this, friendlyByteBuf -> friendlyByteBuf.writeItem(ItemStack.EMPTY));
		      }
		   }				
			
		   // ########## ########## ########## ##########
		   @Override
		   public boolean onEntitySwing(ItemStack helditem, LivingEntity le) {
		      Level warudo = le.level();				
			      if(!warudo.isClientSide()){				
			         CompoundTag nbt = get_nbt(helditem);
		         System.out.println(NbtUtils.prettyPrint(nbt));				
			      }				
			
		      return true;
		   }				
			
		   // ########## ########## ########## ##########
		   public BlockPlaceContext getContext(Level warudo, Player pe, float dist, InteractionHand hand, ItemStack helditem){
		      Vec3 vi = pe.getEyePosition();
		      Vec3 vo = pe.getLookAngle();//is a delta
		      //float dist = 6.0F;
		      Vec3 vh;
		      vh = new Vec3( (vi.x + (vo.x * dist) ), (vi.y + (vo.y * dist) ), (vi.z + (vo.z * dist) ) );
		      BlockState clicked_blkstate;
		      //if( !warudo.isClientSide()  )
		      {
		         HitResult hitresult = warudo.clip(
		                 new ClipContext(vi, vh, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, pe));
		         if (hitresult.getType() == HitResult.Type.BLOCK) {
		            BlockPlaceContext context = new BlockPlaceContext(pe, hand, helditem, (BlockHitResult) hitresult);
		            return context;
		         }
		      }
		      return null;
		   }				
			   // ########## ########## ########## ##########
		   public ItemStack set_as_block(Level warudo, Player pe, InteractionHand hand, ItemStack helditem){
		      if( !warudo.isClientSide()  ) {// && can_do_it(helditem)				
			            BlockPlaceContext context = getContext(warudo, pe, 5.0F ,hand, helditem);
		            BlockState blkstate = this.getBlock().getStateForPlacement(context);//ask the blockstate from the block				
			            BlockPos pos = context.getClickedPos();				
			            BlockState clicked_blkstate = warudo.getBlockState(pos);
		            if ( clicked_blkstate.canBeReplaced()  ) {
		               warudo.setBlock(pos, blkstate, 2);				
			               fill_blockentity_whit(warudo, pos, helditem);
		               helditem.shrink(1);
		            }
		         }				
			      return helditem;
		   }				
			
		   // ########## ########## ########## ##########
		   //@Override
		   public void fill_blockentity_whit(Level warudo, BlockPos pos, ItemStack container) {
		      BlockState blkstate = this.getBlock().defaultBlockState();
		      BlockEntity blockentity = warudo.getBlockEntity(pos);				
			      container.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(handleritem -> {
		         BlockEntityBodyBlock bebb = null;				
			         if(blockentity instanceof BlockEntityBodyBlock){
		            bebb = (BlockEntityBodyBlock)blockentity;
		         }				
			         if(!(blockentity instanceof BlockEntityBodyBlock)){
		            warudo.removeBlockEntity(pos);
		            bebb = new BlockEntityBodyBlock(pos, blkstate);
		            warudo.setBlockEntity(bebb);
		         }				
			         bebb.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(handlerblock -> {
		            ItemStack cosa = null;
		            for (int i = 0; i < handlerblock.getSlots(); ++i) {
		               cosa = handleritem.getStackInSlot(i);
		               handlerblock.insertItem(i, cosa, false);
		            }
		         });
		      });
		   }				
			   // ########## ########## ########## ##########
		   // ########## ########## ########## ##########
		}
		 				
			

 

 

 

 

 

 

 

 

 

Edited by perromercenary00
Gramar missmatch
Link to comment
Share on other sites

WIthout entering on menu class and capability shenanigans, in the load method try calling the super.load(nbt) before doing anything else. It might not be it, but that's really the only difference i can see with the very basic be i have. If you have a repo i can make a clone of to take a quick look at the whole thing on I'll maybe help you out quicker

Link to comment
Share on other sites

i has that 
anyway i test it at the beginning and the end of the function just to be sure 

	@Override
public void load( CompoundTag nbt ){
super.load( nbt );

Level warudo = this.getLevel();
itemhandler.deserializeNBT( nbt.getCompound("itemhandler") );
this.progress = nbt.getInt("progress" );

System.out.println("load(nbt)");
System.out.println(NbtUtils.prettyPrint(nbt));
	//super.load( nbt );
}
	

but it does the same 

 

looking at it a second time
it seems like it only store the nbt data when the entity is created and set into the world 
then never update values

 

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

    • Join one of the largest civilization experiments in Minecraft under our banner!   Our goal is to create the largest and most prominent civilization across the entirety of Minecraft, and we’d like you to join! We offer lots of unique roles and jobs that tailor to your specific skillset in Minecraft! You can build a city, participate in the government, or fight for Gold, God, and Glory on the battlefield!   Join our nation today! https://discord.gg/hb3cuaDezA
    • I have an issue where after I exit the world the capability data does not save when I reload the world. It will save the initial data such as village name but if I modify any data during gameplay theres a 5% chance the data saves when I exit then reload the world. I read the docs and was told that chunks need to be marked dirty but the docs does not say how to mark the chunk dirty... Heres the provider: public class ChunkCapProvider implements ICapabilityProvider, ICapabilitySerializable<CompoundTag> { private final Capability<IChunk> capability = ChunkCapability.CHUNK_CAPABILITY; private final ChunkCapability instance = new ChunkCapability(); private final LazyOptional lazy = LazyOptional.of(()->instance).cast(); public void invalidate(){ lazy.invalidate(); } @Nonnull @Override public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction direction) { if(cap == capability ) return lazy; return LazyOptional.empty(); } @Override public CompoundTag serializeNBT() { return instance.serializeNBT(); } @Override public void deserializeNBT(CompoundTag tag) { instance.deserializeNBT(tag); } }   Heres the capability class: public class ChunkCapability implements IChunk { public static final ResourceLocation ID = new ResourceLocation(Main.MODID, "owner"); public static final String VILLAGE_NAME = "village_name"; public static final String SAVED_ROLES = "saved_roles"; public static final String SAVED_POINTS = "saved_points"; public static final String BAD_CHUNK = "BAD_VILLAGE_CHUNK"; public static Capability<IChunk> CHUNK_CAPABILITY = null; private String villageName = "BAD_VILLAGE_CHUNK"; private String savedRoles = ""; private String savedPoints = ""; public ChunkCapability(){ this.getClass(); } @Override public CompoundTag serializeNBT() { CompoundTag nbt = new CompoundTag(); nbt.putString(SAVED_ROLES, this.savedRoles); nbt.putString(SAVED_POINTS, this.savedPoints); nbt.putString(VILLAGE_NAME, this.villageName); return nbt; } public void deserializeNBT(CompoundTag tag) { this.setVillageName(tag.getString(VILLAGE_NAME)); this.setSavedRoles(tag.getString(SAVED_ROLES)); this.setSavedPoints(tag.getString(SAVED_POINTS)); } public String getVillageName() { return this.villageName; } public void setVillageName(String str) { this.villageName = str; } public void setSavedRoles(String str) { this.savedRoles = str; } public void setRole(String name, String role){ if(!this.hasRole(name)) { this.savedRoles += (name + ":" + role + ","); this.savedPoints += (name + ":" + 10 + ","); return; } String roleName = this.getRole(name); String firstStr = this.savedRoles.substring(0, this.savedRoles.indexOf(name + ":") + name.length() + 1); String lastStr = this.savedRoles.substring(this.savedRoles.indexOf(name + ":") + ((name.length() + 1) + roleName.length())); this.savedRoles = firstStr + role + lastStr; } public String getRole(String name){ if(this.savedRoles.isEmpty() || !this.savedRoles.contains(name)) { this.setRole(name, Roles.Role.FOREIGNER.getName()); } String fStr = this.savedRoles.substring(this.savedRoles.indexOf(name + ":"), this.savedRoles.indexOf(',')); return fStr.substring(fStr.indexOf(':') + 1); } public boolean hasRole(String name) { if(this.savedRoles.isEmpty()) return false; return this.savedRoles.contains(name); } public String getSavedRoles() { return this.savedRoles; } public String getSavedPoints() { return this.savedPoints; } public void setSavedPoints(String name) { this.savedPoints = name; } public int getPoints(String name) { if(this.savedPoints.isEmpty() || !this.savedRoles.contains(name)) this.setPoints(name, 10); String fStr = this.savedPoints.substring(this.savedPoints.indexOf(name + ':')); return Integer.parseInt(fStr.substring(fStr.indexOf(':') + 1, fStr.indexOf(','))); } public void setPoints(String name, int rV) { if(!this.hasPoints(name)){ this.savedPoints += (name + ":" + rV + ","); return; } String oldPoints = String.valueOf(this.getPoints(name)); String points = String.valueOf(rV); String firstStr = this.savedPoints.substring(0, this.savedPoints.indexOf(name + ":") + name.length() + 1); String lastStr = this.savedPoints.substring(this.savedPoints.indexOf(name + ":") + ((name.length() + 1) + oldPoints.length())); Minecraft.getInstance().player.displayClientMessage(Component.nullToEmpty("Saved String: " + (firstStr + points + lastStr)), false); this.savedPoints = (firstStr + points + lastStr); } public boolean hasPoints(String name) { if(this.savedPoints.isEmpty()) return false; return this.savedPoints.contains(name); } }   Heres where I attach/register: @Mod.EventBusSubscriber(modid = Main.MODID) public class CapabilityEvents { @SubscribeEvent public static void attachCapability(AttachCapabilitiesEvent<LevelChunk> event){ ChunkCapProvider provider = new ChunkCapProvider(); event.addCapability(ChunkCapability.ID, provider); event.addListener(provider::invalidate); } }  
    • Id use this ServerLevel#findNearestMapFeature  
    • Trying to play with the mods: Tinkers Construct, Buildcraft and the Blood Magic addon Blood Arsenal; the game crashes. I noticed that when trying to use only two of the three in any combination the game opens without problems, but when trying to put all three together the error occurs. Is there any configuration I can modify or any other way to solve the problem?   ---- Minecraft Crash Report ---- // Hi. I'm Minecraft, and I'm a crashaholic. Time: 5/22/24 8:48 PM Description: There was a severe problem during mod loading that has caused the game to fail cpw.mods.fml.common.LoaderException: java.lang.NoClassDefFoundError: tconstruct/library/weaponry/AmmoWeapon     at cpw.mods.fml.common.LoadController.transition(LoadController.java:163)     at cpw.mods.fml.common.Loader.loadMods(Loader.java:544)     at cpw.mods.fml.client.FMLClientHandler.beginMinecraftLoading(FMLClientHandler.java:208)     at net.minecraft.client.Minecraft.func_71384_a(Minecraft.java:480)     at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:878)     at net.minecraft.client.main.Main.main(SourceFile:148)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)     at java.lang.reflect.Method.invoke(Unknown Source)     at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)     at net.minecraft.launchwrapper.Launch.main(Launch.java:28) Caused by: java.lang.NoClassDefFoundError: tconstruct/library/weaponry/AmmoWeapon     at java.lang.Class.forName0(Native Method)     at java.lang.Class.forName(Unknown Source)     at cpw.mods.fml.common.ProxyInjector.inject(ProxyInjector.java:42)     at cpw.mods.fml.common.FMLModContainer.constructMod(FMLModContainer.java:512)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)     at java.lang.reflect.Method.invoke(Unknown Source)     at com.google.common.eventbus.EventSubscriber.handleEvent(EventSubscriber.java:74)     at com.google.common.eventbus.SynchronizedEventSubscriber.handleEvent(SynchronizedEventSubscriber.java:47)     at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322)     at com.google.common.eventbus.EventBus.dispatchQueuedEvents(EventBus.java:304)     at com.google.common.eventbus.EventBus.post(EventBus.java:275)     at cpw.mods.fml.common.LoadController.sendEventToModContainer(LoadController.java:212)     at cpw.mods.fml.common.LoadController.propogateStateMessage(LoadController.java:190)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)     at java.lang.reflect.Method.invoke(Unknown Source)     at com.google.common.eventbus.EventSubscriber.handleEvent(EventSubscriber.java:74)     at com.google.common.eventbus.SynchronizedEventSubscriber.handleEvent(SynchronizedEventSubscriber.java:47)     at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322)     at com.google.common.eventbus.EventBus.dispatchQueuedEvents(EventBus.java:304)     at com.google.common.eventbus.EventBus.post(EventBus.java:275)     at cpw.mods.fml.common.LoadController.distributeStateMessage(LoadController.java:119)     at cpw.mods.fml.common.Loader.loadMods(Loader.java:513)     ... 10 more Caused by: java.lang.ClassNotFoundException: tconstruct.library.weaponry.AmmoWeapon     at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:191)     at java.lang.ClassLoader.loadClass(Unknown Source)     at java.lang.ClassLoader.loadClass(Unknown Source)     ... 36 more Caused by: java.lang.NoClassDefFoundError: tconstruct/library/weaponry/AmmoItem     at java.lang.ClassLoader.defineClass1(Native Method)     at java.lang.ClassLoader.defineClass(Unknown Source)     at java.security.SecureClassLoader.defineClass(Unknown Source)     at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:182)     ... 38 more Caused by: java.lang.ClassNotFoundException: tconstruct.library.weaponry.AmmoItem     at net.minecraft.launchwrapper.LaunchClassLoader.findClass(LaunchClassLoader.java:101)     at java.lang.ClassLoader.loadClass(Unknown Source)     at java.lang.ClassLoader.loadClass(Unknown Source)     ... 42 more A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- System Details -- Details:     Minecraft Version: 1.7.10     Operating System: Windows 10 (x86) version 10.0     Java Version: 1.8.0_411, Oracle Corporation     Java VM Version: Java HotSpot(TM) Client VM (mixed mode, sharing), Oracle Corporation     Memory: 271923192 bytes (259 MB) / 402653184 bytes (384 MB) up to 536870912 bytes (512 MB)     JVM Flags: 9 total; -Xmx512M -XX:+UnlockExperimentalVMOptions -XX:+UseG1GC -XX:G1NewSizePercent=20 -XX:G1ReservePercent=20 -XX:MaxGCPauseMillis=50 -XX:G1HeapRegionSize=32M -XX:+IgnoreUnrecognizedVMOptions -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump     AABB Pool Size: 0 (0 bytes; 0 MB) allocated, 0 (0 bytes; 0 MB) used     IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0     FML: MCP v9.05 FML v7.10.99.99 Minecraft Forge 10.13.4.1614 14 mods loaded, 14 mods active     States: 'U' = Unloaded 'L' = Loaded 'C' = Constructed 'H' = Pre-initialized 'I' = Initialized 'J' = Post-initialized 'A' = Available 'D' = Disabled 'E' = Errored     UC    mcp{9.05} [Minecraft Coder Pack] (minecraft.jar)      UC    FML{7.10.99.99} [Forge Mod Loader] (forge-1.7.10-10.13.4.1614-1.7.10.jar)      UC    Forge{10.13.4.1614} [Minecraft Forge] (forge-1.7.10-10.13.4.1614-1.7.10.jar)      UC    AWWayofTime{v1.3.3} [Blood Magic: Alchemical Wizardry] (BloodMagic-1.7.10-1.3.3-17.jar)      UC    Mantle{1.7.10-0.3.2.jenkins191} [Mantle] (Mantle-1.7.10-0.3.2b.jar)      UE    TConstruct{1.7.10-1.8.8.build991} [Tinkers' Construct] (TConstruct-1.7.10-1.8.8.build991.jar)      UC    BloodArsenal{1.2-5} [Blood Arsenal] (BloodArsenal-1.7.10-1.2-5.jar)      UC    BuildCraft|Core{7.1.25} [BuildCraft] (buildcraft-7.1.25.jar)      UC    BuildCraft|Builders{7.1.25} [BC Builders] (buildcraft-7.1.25.jar)      UC    BuildCraft|Robotics{7.1.25} [BC Robotics] (buildcraft-7.1.25.jar)      UC    BuildCraft|Silicon{7.1.25} [BC Silicon] (buildcraft-7.1.25.jar)      UC    BuildCraft|Energy{7.1.25} [BC Energy] (buildcraft-7.1.25.jar)      UC    BuildCraft|Transport{7.1.25} [BC Transport] (buildcraft-7.1.25.jar)      UC    BuildCraft|Factory{7.1.25} [BC Factory] (buildcraft-7.1.25.jar)      GL info: ' Vendor: 'Intel' Version: '4.4.0 - Build 21.20.16.4541' Renderer: 'Intel(R) HD Graphics 610'     Mantle Environment: Environment healthy.     TConstruct Environment: Environment healthy.
    • fixed this problem but now i have a new one  java.lang.RuntimeException: java.lang.NoSuchFieldException: processor  Help 
  • Topics

×
×
  • Create New...

Important Information

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