Jump to content

saving custom classes in nbt?


Atijaf

Recommended Posts

You can always split objects in to basic objects. All basic objects, you can save in nbt. For example BlockPos, can be split into

int x, int y, int z

. And IBlockState can be converted to

int meta

by using get metaFromState.

Link to comment
Share on other sites

Just overwrite the method writeToNBT and readFromNBT to save/load your data.

 

For example:

@Override
    public void writeToNBT(NBTTagCompound nbtTagCompound)
    {
        super.writeToNBT(nbtTagCompound);

        nbtTagCompound.setInteger("WorldID", world.getId())
        ........
    }

Link to comment
Share on other sites

Just overwrite the method writeToNBT and readFromNBT to save/load your data.

 

For example:

@Override
    public void writeToNBT(NBTTagCompound nbtTagCompound)
    {
        super.writeToNBT(nbtTagCompound);

        nbtTagCompound.setInteger("WorldID", world.getId())
        ........
    }

I think he has custom class and no writeToNbt and readToNbt methods (and maybe no super methods). And he asks about how he can save "complex" variables like objects to nbt.

Link to comment
Share on other sites

I have a list of blocks and block locations that are suppose to regenerate in specific areas.  I have a command that I can use to add them to a list and once I save and quit, I would like to store this information so that it may be used the next time I load into the world.

Link to comment
Share on other sites

Alright I think I'm getting somewhere.

 

I've noticed that you didn't use the methods nbt.setTag or nbt.getTag inside readFromNBT and writeToNBT.

I also see that you are using a method inside QuestologyWorldData get(World world), called world.setItemData(IDENTIFIER, data)

 

Why not use nbt.setTag/getTag and what is "world.setItemData"

 

Also, is markDirty() saving the information?

 

Thank you!  Sorry for the load of questions!

Link to comment
Share on other sites

When I use my command to add new information, it runs through the write method and adds the data I want it to inside of the nbt and It also works correctly while reading the information.  But, when I restart the game, it doesn't find anything there.  My only guess would be that the world Data information I am using is different every time I load the game.  Here is some code.

 

Event Handler

 

 

@SubscribeEvent

public void onWorldLoad(WorldEvent.Load event){

PacketDispatcher.sendToAll(new SyncWorldData(event.world));

}

 

 

 

PacketDispatcher / sendTo methods

 

 

public class PacketDispatcher

{

// a simple counter will allow us to get rid of 'magic' numbers used during packet registration

private static byte packetId = 0;

private boolean used;

 

/**

* The SimpleNetworkWrapper instance is used both to register and send packets.

* Since I will be adding wrapper methods, this field is private, but you should

* make it public if you plan on using it directly.

*/

private static final SimpleNetworkWrapper dispatcher = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID);

 

 

/**

* Call this during pre-init or loading and register all of your packets (messages) here

*/

public static final void registerPackets() {

registerMessage(SyncMiningStats.class);

registerMessage(SyncExcavationStats.class);

registerMessage(SyncWoodCuttingStats.class);

registerMessage(SyncWorldData.class);

 

}

 

/**

* Registers an {@link AbstractMessage} to the appropriate side(s)

*/

private static final <T extends AbstractMessage<T> & IMessageHandler<T, IMessage>> void registerMessage(Class<T> clazz) {

// We can tell by the message class which side to register it on by using #isAssignableFrom (google it)

 

// Also, one can see the convenience of using a static counter 'packetId' to keep

// track of the current index, rather than hard-coding them all, plus it's one less

// parameter to pass.

if (AbstractMessage.AbstractClientMessage.class.isAssignableFrom(clazz)) {

PacketDispatcher.dispatcher.registerMessage(clazz, clazz, packetId++, Side.CLIENT);

} else if (AbstractMessage.AbstractServerMessage.class.isAssignableFrom(clazz)) {

PacketDispatcher.dispatcher.registerMessage(clazz, clazz, packetId++, Side.SERVER);

} else {

// hopefully you didn't forget to extend the right class, or you will get registered on both sides

PacketDispatcher.dispatcher.registerMessage(clazz, clazz, packetId, Side.CLIENT);

PacketDispatcher.dispatcher.registerMessage(clazz, clazz, packetId++, Side.SERVER);

}

}

 

//========================================================//

// The following methods are the 'wrapper' methods; again,

// this just makes sending a message slightly more compact

// and is purely a matter of stylistic preference

//========================================================//

 

 

 

/**

* Send this message to the specified player's client-side counterpart.

* See {@link SimpleNetworkWrapper#sendTo(IMessage, EntityPlayerMP)}

*/

public static final void sendTo(IMessage message, EntityPlayerMP player) {

PacketDispatcher.dispatcher.sendTo(message, player);

}

 

/**

* Send this message to everyone.

* See {@link SimpleNetworkWrapper#sendToAll(IMessage)}

*/

public static void sendToAll(IMessage message) {

PacketDispatcher.dispatcher.sendToAll(message);

}

 

/**

* Send this message to everyone within a certain range of a point.

* See {@link SimpleNetworkWrapper#sendToAllAround(IMessage, NetworkRegistry.TargetPoint)}

*/

public static final void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point) {

PacketDispatcher.dispatcher.sendToAllAround(message, point);

}

 

/**

* Sends a message to everyone within a certain range of the coordinates in the same dimension.

* Shortcut to {@link SimpleNetworkWrapper#sendToAllAround(IMessage, NetworkRegistry.TargetPoint)}

*/

public static final void sendToAllAround(IMessage message, int dimension, double x, double y, double z, double range) {

PacketDispatcher.sendToAllAround(message, new NetworkRegistry.TargetPoint(dimension, x, y, z, range));

}

 

/**

* Sends a message to everyone within a certain range of the player provided.

* Shortcut to {@link SimpleNetworkWrapper#sendToAllAround(IMessage, NetworkRegistry.TargetPoint)}

*/

public static final void sendToAllAround(IMessage message, EntityPlayer player, double range) {

PacketDispatcher.sendToAllAround(message, player.worldObj.provider.getDimensionId(), player.posX, player.posY, player.posZ, range);

}

 

/**

* Send this message to everyone within the supplied dimension.

* See {@link SimpleNetworkWrapper#sendToDimension(IMessage, int)}

*/

public static final void sendToDimension(IMessage message, int dimensionId) {

PacketDispatcher.dispatcher.sendToDimension(message, dimensionId);

}

 

/**

* Send this message to the server.

* See {@link SimpleNetworkWrapper#sendToServer(IMessage)}

*/

public static final void sendToServer(IMessage message) {

PacketDispatcher.dispatcher.sendToServer(message);

}

}

 

 

 

SnycWorldData Class

 

 

public class SyncWorldData extends AbstractClientMessage<SyncWorldData>{

 

private NBTTagCompound world_data;

 

public SyncWorldData(){}

 

public SyncWorldData(World world){

world_data = new NBTTagCompound();

WorldData.get(world).writeToNBT(world_data);

//get method

 

 

public static WorldData get(World world){

WorldData data = (WorldData)world.loadItemData(WorldData.class, Identifier);

if (data == null){

data = new WorldData();

world.setItemData(Identifier, data);

}

return data;

}

 

 

 

//WriteToNBT method

 

 

public void writeToNBT(NBTTagCompound nbt) {

 

NBTTagList tagList = new NBTTagList();

NBTTagCompound tag = new NBTTagCompound();

 

for(Tuple test : currentRespawnLocs.keySet()){

BlockPos pos = test.getPos();

IBlockState state = test.getState();

int blockId = Requirements.getBlockId(state);

int blockMeta = Requirements.getBlockMeta(state);

int worldId = test.getWorldId();

 

                        //STORES INFORMATION IN ARRAY OF INTS

int[] tempPos = new int[]{pos.getX(),pos.getY(),pos.getZ(), blockId, blockMeta, worldId};

posArray.add(tempPos);

}

 

for(int i = 0; i < posArray.size(); i++){

int[] currentMyBlockPos = posArray.get(i);

if(currentMyBlockPos != null && nbt.getIntArray("myBlockPos" + i) != null){

 

tag.setIntArray("myBlockPos" + i, currentMyBlockPos);

                                //APPEND IF TagList HAS NO LENGTH YET

if(tagList.hasNoTags())

tagList.appendTag(tag);

else

tagList.set(0, tag);

}

}

//STORE TagList INSIDE NBT

nbt.setTag(Identifier, tagList);

}

 

 

 

 

}

 

protected void read(PacketBuffer buffer) throws IOException{

world_data = buffer.readNBTTagCompoundFromBuffer();

}

 

protected void write(PacketBuffer buffer) throws IOException{

buffer.writeNBTTagCompoundToBuffer(world_data);

}

 

public void process(EntityPlayer player, Side side){

WorldData.get(player.worldObj).readFromNBT(world_data);

//READ

 

 

/**

This undoes what the write method does.  It takes all the integers and converts them to blockPos, an IBlockState, and worldId.  It then adds them to the hashMap currentRespawnLocs(a public class variable.

*/

public void readFromNBT(NBTTagCompound nbt) {

NBTTagList tagList = nbt.getTagList(Identifier, Constants.NBT.TAG_COMPOUND);

for(int i = 0; tagList.getCompoundTagAt(0).hasKey("myBlockPos" + i); i++){

int[] currentMyBlockPos = tagList.getCompoundTagAt(0).getIntArray("myBlockPos" + i);

BlockPos pos = new BlockPos(currentMyBlockPos[0], currentMyBlockPos[1], currentMyBlockPos[2]);

int blockId = currentMyBlockPos[3];

int blockMeta = currentMyBlockPos[4];

int worldId = currentMyBlockPos[5];

 

Block tempBlock = Block.getBlockById(blockId);

IBlockState state = tempBlock.getStateFromMeta(blockMeta);

 

currentRespawnLocs.put(new Tuple(this.pos, this.state, this.worldId), true);

}

}

 

 

}

 

}

 

 

 

I know that this is a lot of information.  I don't expect you, nor anyone, to read all of it.  I am just curious if you can spot any errors.  The packetDispatcher should be just fine, as I have used it to store information with players.

Link to comment
Share on other sites

There was one more class that I forgot to include in pastebin.

Also, every time i start minecraft and debug.  It goes through the method, WorldData get(World world), and data is null so it creates a new one.  Is that suppose to happen?

I also never call the method, setDirty();

 

I went ahead and changed the static variable to a private class variable.  No change...  I'll leave it a private class variable though

 

Here's my SyncWorldData class

http://pastebin.com/dgNBV6G2

Link to comment
Share on other sites

I've messed with the code a little bit and created a method called saveData.

I call this method after I add data to nbt.

 

 

 

public void saveData(World world){

WorldData data = (WorldData) world.loadItemData(WorldData.class, Identifier);

world.setItemData(Identifier, data);

data.markDirty();

world.getPerWorldStorage().saveAllData();

}

 

 

 

I run that bit of code, save and quit, reload, and data is null again.  The only thing that I can think of that would be wrong is the retrieval of the information..  Or maybe even saving it.  Is there anything wrong with this bit of code.

 

I am coding in 1.8, if that makes a difference.

 

Link to comment
Share on other sites

It will save when you either exist the world or open the ingame menu. In multiplayer it will save at the intervals set in the config.

 

Thanks for explaining that.  That's what I was worried about...

I am thinking that I probably missed something obvious near the beginning.

After I use markDirty(), it sets dirty to true.  I then save it. Re enter the command to add more data and before it even gets to the mothod, markDirty(), dirty is still true. (I'm gussing dirty is suppose to be switched back to false when it saves)

 

I will look at my code for a while and possibly make a new thread that deals more with WorldSavedData.

Link to comment
Share on other sites

All I can figure out is that the method "readFromNBT(NBTTagCompound nbt) is not getting called automatically, but when I manually call it, nbt has nothing saved in it.

 

Am I suppose to register WorldData?  or just use the method "public static WorldData get(World world).

 

Also, when the command to set a few variables is used and I use the method "nbt.setTag(Identifier, tagList)"  nbt gets data, and then closes.  If I call the method again, nbt has no data again, as if I never used the command once.  It's weird...

Link to comment
Share on other sites

You probably want to make all variables statis, make setters for them and in the setters call markDirty().

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

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

    • Dalam dunia perjudian online yang berkembang pesat, mencari platform yang dapat memberikan kemenangan maksimal dan hasil terbaik adalah impian setiap penjudi. OLXTOTO, dengan bangga, mempersembahkan dirinya sebagai jawaban atas pencarian itu. Sebagai platform terbesar untuk kemenangan maksimal dan hasil optimal, OLXTOTO telah menciptakan gelombang besar di komunitas perjudian online. Satu dari banyak keunggulan yang dimiliki OLXTOTO adalah koleksi permainan yang luas dan beragam. Dari togel hingga slot online, dari live casino hingga permainan kartu klasik, OLXTOTO memiliki sesuatu untuk setiap pemain. Dibangun dengan teknologi terkini dan dikembangkan oleh para ahli industri, setiap permainan di platform ini dirancang untuk memberikan pengalaman yang tak tertandingi bagi para penjudi. Namun, keunggulan OLXTOTO tidak hanya terletak pada variasi permainan yang mereka tawarkan. Mereka juga menonjol karena komitmen mereka terhadap keamanan dan keadilan. Dengan sistem keamanan tingkat tinggi dan proses audit yang ketat, OLXTOTO memastikan bahwa setiap putaran permainan berjalan dengan adil dan transparan. Para pemain dapat merasa aman dan yakin bahwa pengalaman berjudi mereka di OLXTOTO tidak akan terganggu oleh masalah keamanan atau keadilan. Tak hanya itu, OLXTOTO juga terkenal karena layanan pelanggan yang luar biasa. Tim dukungan mereka selalu siap sedia untuk membantu para pemain dengan segala pertanyaan atau masalah yang mereka hadapi. Dengan respon cepat dan solusi yang efisien, OLXTOTO memastikan bahwa pengalaman berjudi para pemain tetap mulus dan menyenangkan. Dengan semua fitur dan keunggulan yang ditawarkannya, tidak mengherankan bahwa OLXTOTO telah menjadi pilihan utama bagi jutaan penjudi online di seluruh dunia. Jika Anda mencari platform yang dapat memberikan kemenangan maksimal dan hasil optimal, tidak perlu mencari lebih jauh dari OLXTOTO. Bergabunglah dengan OLXTOTO hari ini dan mulailah petualangan Anda menuju kemenangan besar dan hasil terbaik!
    • Selamat datang di OLXTOTO, situs slot gacor terpanas yang sedang booming di industri perjudian online. Jika Anda mencari pengalaman bermain yang luar biasa, maka OLXTOTO adalah tempat yang tepat untuk Anda. Dapatkan sensasi tidak biasa dengan variasi slot online terlengkap dan peluang memenangkan jackpot slot maxwin yang sering. Di sini, Anda akan merasakan keseruan yang luar biasa dalam bermain judi slot. DAFTAR OLXTOTO DISINI LOGIN OLXTOTO DISINI AKUN PRO OLXTOTO DISINI   Jackpot Slot Maxwin Sering Untuk Peluang Besar Di OLXTOTO, kami tidak hanya memberikan hadiah slot biasa, tapi juga memberikan kesempatan kepada pemain untuk memenangkan jackpot slot maxwin yang sering. Dengan demikian, Anda dapat meraih keberuntungan besar dan memenangkan ribuan rupiah sebagai hadiah jackpot slot maxwin kami. Jackpot slot maxwin merupakan peluang besar bagi para pemain judi slot untuk meraih keuntungan yang lebih besar. Dalam permainan kami, Anda tidak harus terpaku pada kemenangan biasa saja. Kami hadir dengan jackpot slot maxwin yang sering, sehingga Anda memiliki peluang yang lebih besar untuk meraih kemenangan besar dengan hadiah yang menggiurkan. Dalam permainan judi slot, pengalaman bermain bukan hanya tentang keseruan dan hiburan semata. Kami memahami bahwa para pemain juga menginginkan kesempatan untuk meraih keberuntungan besar. Oleh karena itu, OLXTOTO hadir dengan jackpot slot maxwin yang sering untuk memberikan peluang besar kepada para pemain kami. Peluang Besar Menang Jackpot Slot Maxwin Peluang menang jackpot slot maxwin di OLXTOTO sangatlah besar. Anda tidak perlu khawatir tentang batasan atau pembatasan dalam meraih jackpot tersebut. Kami ingin memberikan kesempatan kepada semua pemain kami untuk merasakan sensasi menang dalam jumlah yang luar biasa. Jackpot slot maxwin kami dibuka untuk semua pemain judi slot di OLXTOTO. Anda memiliki peluang yang sama dengan pemain lainnya untuk memenangkan hadiah jackpot yang besar. Kami percaya bahwa semua orang memiliki kesempatan untuk meraih keberuntungan besar, dan itulah mengapa kami menyediakan jackpot slot maxwin yang sering untuk memenuhi harapan dan keinginan Anda.   Kesimpulan OLXTOTO adalah situs slot gacor terbaik yang memberikan pengalaman bermain judi slot online yang tak terlupakan. Dengan variasi slot online terlengkap dan peluang memenangkan jackpot slot maxwin yang sering, OLXTOTO menjadi pilihan terbaik bagi para pemain yang mencari kesenangan dan kemenangan besar dalam perjudian online. Di samping itu, OLXTOTO juga menawarkan layanan pelanggan yang ramah dan responsif, siap membantu setiap pemain dalam mengatasi masalah teknis atau pertanyaan seputar perjudian online. Kami menjaga integritas game dan memberikan lingkungan bermain yang adil serta menjalankan kebijakan perlindungan pelanggan yang cermat. Bergabunglah dengan OLXTOTO sekarang dan nikmati pengalaman bermain slot online yang luar biasa. Jadilah bagian dari komunitas perjudian yang mengagumkan ini dan raih kesempatan untuk meraih kemenangan besar. Dapatkan akses mudah dan praktis ke situs OLXTOTO dan rasakan sensasi bermain judi slot yang tak terlupakan.  
    • OLXTOTO: Platform Maxwin dan Gacor Terbesar Sepanjang Masa Di dunia perjudian online yang begitu kompetitif, mencari platform yang dapat memberikan kemenangan maksimal (Maxwin) dan hasil terbaik (Gacor) adalah prioritas bagi para penjudi yang cerdas. Dalam upaya ini, OLXTOTO telah muncul sebagai pemain kunci yang mengubah lanskap perjudian online dengan menawarkan pengalaman tanpa tandingan.     Sejak diluncurkan, OLXTOTO telah menjadi sorotan industri perjudian online. Dikenal sebagai "Platform Maxwin dan Gacor Terbesar Sepanjang Masa", OLXTOTO telah menarik perhatian pemain dari seluruh dunia dengan reputasinya yang solid dan kinerja yang luar biasa. Salah satu fitur utama yang membedakan OLXTOTO dari pesaingnya adalah komitmen mereka untuk memberikan pengalaman berjudi yang unik dan memuaskan. Dengan koleksi game yang luas dan beragam, termasuk togel, slot online, live casino, dan banyak lagi, OLXTOTO menawarkan sesuatu untuk semua orang. Dibangun dengan teknologi terkini dan didukung oleh tim ahli yang berdedikasi, platform ini memastikan bahwa setiap pengalaman berjudi di OLXTOTO tidak hanya menghibur, tetapi juga menguntungkan. Namun, keunggulan OLXTOTO tidak hanya terletak pada permainan yang mereka tawarkan. Mereka juga terkenal karena keamanan dan keadilan yang mereka berikan kepada para pemain mereka. Dengan sistem keamanan tingkat tinggi dan audit rutin yang dilakukan oleh otoritas regulasi independen, para pemain dapat yakin bahwa setiap putaran permainan di OLXTOTO adalah adil dan transparan. Tidak hanya itu, OLXTOTO juga dikenal karena layanan pelanggan yang luar biasa. Dengan tim dukungan yang ramah dan responsif, para pemain dapat yakin bahwa setiap pertanyaan atau masalah mereka akan ditangani dengan cepat dan efisien. Dengan semua fitur dan keunggulan yang ditawarkannya, tidak mengherankan bahwa OLXTOTO telah menjadi platform pilihan bagi para penjudi online yang mencari kemenangan maksimal dan hasil terbaik. Jadi, jika Anda ingin bergabung dengan jutaan pemain yang telah merasakan keajaiban OLXTOTO, jangan ragu untuk mendaftar dan mulai bermain hari ini!  
    • OLXTOTO adalah bandar slot yang terkenal dan terpercaya di Indonesia. Mereka menawarkan berbagai jenis permainan slot yang menarik dan menghibur. Dengan tampilan yang menarik dan grafis yang berkualitas tinggi, pemain akan merasa seperti berada di kasino sungguhan. OLXTOTO juga menyediakan layanan pelanggan yang ramah dan responsif, siap membantu pemain dengan segala pertanyaan atau masalah yang mereka hadapi. Daftar =  https://surkale.me/Olxtotodotcom1
    • DAFTAR & LOGIN BIGO4D   Bigo4D adalah situs slot online yang populer dan menarik perhatian banyak pemain slot di Indonesia. Dengan berbagai game slot yang unik dan menarik, Bigo4D menjadi tempat yang ideal untuk pemula dan pahlawan slot yang berpengalaman. Dalam artikel ini, kami akan membahas tentang Bigo4D sebagai situs slot terbesar dan menarik yang saat ini banyak dijajaki oleh pemain slot online.
  • Topics

×
×
  • Create New...

Important Information

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