Jump to content

[1.10.2] Capabilities unsynced when opening Creative inventory


Tomlabete

Recommended Posts

Hello !

 

I'm on a keys&locks mod that works pairwise with a sponge plugin (not relevant here, though, just remember that it's mainly serversided mecanics).

My items have a code-capability that stores a key-code in them that is checked whenever a player tries to open a closed chest/door/trapdoor. Everything works perfectly well with survival inventories : the plugin sends codes to the server-side items, they keep it and re-send it when asked by the plugin.

 

But the problem occurs with Creative inventory : as soon as a Creative inventory is opened, all keys and locks contained in it are reset to a code "0".

It happens because the client-side capability is never updated and stays at zero. My question is : what is the best way for me to send the code from the server to the client when code is configured ?

 

I'm not good at all with packages. I guess it will be about it, so if you guys could give me some tutorial links with a quick explanation of what I should do in my particular case, I would be really grateful :)

 

Thanks, have a nive day !

Link to comment
Share on other sites

> Tomlabete: post code

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

Ok, np. Here is my Item class, keys and locks are instances of it.

public class McfrCodedItem extends McfrItem {

  public McfrCodedItem(String name, CreativeTabs tab) {
    super(name, 1, tab);
    setHasSubtypes(true);
  }
  
  @Override
  public String getUnlocalizedName(ItemStack stack) {
    return getUnlocalizedName() + "." + (stack.getMetadata() == 0 ? "blank" : "coded");
  }
  
  @Override
  @SideOnly(Side.CLIENT)
  public void getSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) {
    subItems.add(new ItemStack(itemIn, 1, 0)); // metadata = 0 --> Blank key/lock, unusable
    subItems.add(new ItemStack(itemIn, 1, 1)); // metadata = 1 --> Coded key/lock, usable
  }
  
  public void setCode(EntityPlayer player, int code) {
    ItemStack stack = new ItemStack(player.getHeldItemMainhand().getItem(), 1, 1); // replace item in hand with coded item
    
    if (stack.hasCapability(KeyCode.Provider.KEY_CODE_CAP, null)) {
      IKeyCode keyCode = stack.getCapability(KeyCode.Provider.KEY_CODE_CAP, null);
      keyCode.set(code);
    }
    
    player.setHeldItem(EnumHand.MAIN_HAND, stack);
  }

  @SideOnly(Side.SERVER)
  public Optional<Integer> getCode(EntityPlayer player) {
    ItemStack stack = player.getHeldItemMainhand();
    if (stack.getMetadata() == 1 && stack.hasCapability(KeyCode.Provider.KEY_CODE_CAP, null)) // Check if item is coded
      return Optional.of(stack.getCapability(KeyCode.Provider.KEY_CODE_CAP, null).get()); //Optional.of(code) if coded
    else
      return Optional.empty(); //Optional.empty() if blank
  }
}

 

The setCode(player, code) and getCode(player) methods are called from my Sponge plugin. I would like to sync client-item-capabilities with server-item-capabilities whenever setCode is called.

 

Here is my capability class. Provider and Storage are static classes inside it.

public class KeyCode implements IKeyCode {
  private int code = 0;

  @Override
  public int get() {
    return this.code;
  }

  @Override
  public void set(int code) {
    this.code = code;
  }
  
  public static class Storage implements IStorage<IKeyCode> {

    @Override
    public NBTBase writeNBT(Capability<IKeyCode> capability, IKeyCode instance, EnumFacing side) {
      NBTTagCompound tag = new NBTTagCompound();
      tag.setInteger("keyCode", instance.get());
      return tag;
    }

    @Override
    public void readNBT(Capability<IKeyCode> capability, IKeyCode instance, EnumFacing side, NBTBase nbt) {
      NBTTagCompound tag = (NBTTagCompound) nbt;
      instance.set(tag.getInteger("keyCode"));
    }
  }
  
  public static class Provider implements ICapabilitySerializable<NBTBase> {
    
    @CapabilityInject(IKeyCode.class)
    public static final Capability<IKeyCode> KEY_CODE_CAP = null;
    
    private IKeyCode instance = KEY_CODE_CAP.getDefaultInstance();

    @Override
    public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
      return capability == KEY_CODE_CAP;
    }

    @Override
    public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
      return capability == KEY_CODE_CAP ? KEY_CODE_CAP.<T>cast(this.instance) : null;
    }

    @Override
    public NBTBase serializeNBT() {
      return KEY_CODE_CAP.getStorage().writeNBT(KEY_CODE_CAP, this.instance, null);
    }

    @Override
    public void deserializeNBT(NBTBase nbt) {
      KEY_CODE_CAP.getStorage().readNBT(KEY_CODE_CAP, this.instance, null, nbt);
    }
  }
}

Handling of the attachCapabilities event :

public class ItemEventsHandler {
  public static final ResourceLocation KEY_CODE_CAP = new ResourceLocation(Constants.MOD_ID, "keyCode");
  
  @SubscribeEvent
  public void onAttachEntityCapabilities(AttachCapabilitiesEvent<Item> event) {
    if (event.getObject() instanceof McfrCodedItem) {
      event.addCapability(KEY_CODE_CAP, new KeyCode.Provider());
    }
  }
}

And finally, the line in my Init method, in main class :

CapabilityManager.INSTANCE.register(IKeyCode.class, new KeyCode.Storage(), KeyCode.class);

Hope this helps :)

Edited by Tomlabete
Link to comment
Share on other sites

That's true, I don't use initCapabilities at all, I'm going to try this, but will data be transmitted from the server to the client and then back to the server with only this ?

 

Here is the gitHub folder where you can find the capability (KeyCode), its interface (IKeyCode) and the Item class (McfrCodedItem).

https://github.com/Mc-Fr/Forge/tree/master/Forge1.10/src/main/java/net/mcfr/mecanisms/keys

 

Here is the event handler that I need to delete and replace by usage of initCapabilities (doing this tomorrow).

https://github.com/Mc-Fr/Forge/blob/master/Forge1.10/src/main/java/net/mcfr/event/ItemEventsHandler.java

Link to comment
Share on other sites

Here's your tutorial for networking, since nobody linked it before: https://mcforge.readthedocs.io/en/latest/networking/simpleimpl/

 

Honestly. Packets are very important and you should learn it at some point or another. With a lot of capabilities it's hard to get the client updated, My sollution was to send all capability updates in a synchronisation packet when the player logs in. 

 

Here's an example that I'm currently using to send capability info to the client: 

public class SmallMessage implements IMessage {
    public SmallMessage(){}
    private NBTTagCompound toSend;
    public SmallMessage(NBTTagCompound tag){
        this.toSend = tag;
    }

    @Override
    public void toBytes(ByteBuf buf) {
        ByteBufUtils.writeTag(buf, this.toSend);
    }

    @Override
    public void fromBytes(ByteBuf buf) {
        this.toSend = ByteBufUtils.readTag(buf);
    }

    public static class MessageHandler implements IMessageHandler<SmallMessage, IMessage> {

        @Override
        public IMessage onMessage(final SmallMessage content, final MessageContext ctx) {

            FMLCommonHandler.instance().getWorldThread(ctx.netHandler).addScheduledTask(new Runnable(){
                @Override
                public void run(){
                    final IBarHandler handler = Minecraft.getMinecraft().thePlayer.getCapability(CAPABILITY_BAR, null);
                    NBTTagCompound tag = content.toSend;
                    handler.setMana(tag.getInteger("mana"));
                    handler.setHealth(tag.getInteger("health"));
                    handler.setFatigue(tag.getInteger("fatigue"));
                }
            });
                return null;
        }

    }
}

 

and I call it using 

        if(player.hasCapability(CAPABILITY_BAR, null)) {
            final IBarHandler instance = getHandler(player);
            final NBTTagCompound tag = new NBTTagCompound();
            tag.setInteger("mana", instance.getMana());
            tag.setInteger("health", instance.getHealth());
            tag.setInteger("fatigue", instance.getFatigue());
            Main.packetHandler.barWrapper.sendTo(new SmallMessage(tag), (EntityPlayerMP) player);
        }

 

Obviously you could easily add whatever information to the NBTTagCompound or even work with TagLists and such. The rest of the code is initiated in the way you see in the documentations linked above. If you read it through thoroughly you should be able to get a packet working.

  • Like 1
Link to comment
Share on other sites

Well, I did it all and this is not working. Packet is sent and received, the code is transmitted from server to client, but I can't find a way to update the ItemStack. It seems that it's overwritten by the server without taking the capability into account. The code of the key/lock is always 0 (default) on the client. On the server it can be anything, but as soon as I open Creative inventory, all codes are reset...

 

I tried to change the quantity and the item type of the stack but nothing is happening, I guess the client hasn't any right to tell which ItemStack is in the inventory of the player.

 

Any idea for me ?

(I found this thread on a same topic, unsolved yet...)

 

Link to comment
Share on other sites

I think this can help me, but after a deep look in all the related threads, I can't figure out how exactly can I attach my capability data to the stack NBT.

 

When I try this on the server, I am disconnected with an error on the server console as soon as I take a key/lock in my hand :

@Override
  public NBTTagCompound getNBTShareTag(ItemStack stack) {
    stack.getTagCompound().setInteger("keyCode", stack.getCapability(KeyCode.Provider.KEY_CODE_CAP, null).get());
    return stack.getTagCompound();
  }

 

The error :

b307a23154.png

Edited by Tomlabete
Link to comment
Share on other sites

stack.getTagCompound() is not guaranteed to return anything.

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

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

    • This honestly might just work for you @SubscribeEvent public static void onScreenRender(ScreenEvent.Render.Post event) { final var player = Minecraft.getInstance().player; if(!hasMyEffect(player)) return; // TODO: You provide hasMyEffect float f = Mth.lerp(p_109094_, this.minecraft.player.oSpinningEffectIntensity, this.minecraft.player.spinningEffectIntensity); float f1 = ((Double)this.minecraft.options.screenEffectScale().get()).floatValue(); if(f <= 0F || f1 >= 1F) return; float p_282656_ = ?; final var p_282460_ = event.getGuiGraphics(); int i = p_282460_.guiWidth(); int j = p_282460_.guiHeight(); p_282460_.pose().pushPose(); float f = Mth.lerp(p_282656_, 2.0F, 1.0F); p_282460_.pose().translate((float)i / 2.0F, (float)j / 2.0F, 0.0F); p_282460_.pose().scale(f, f, f); p_282460_.pose().translate((float)(-i) / 2.0F, (float)(-j) / 2.0F, 0.0F); float f1 = 0.2F * p_282656_; float f2 = 0.4F * p_282656_; float f3 = 0.2F * p_282656_; RenderSystem.disableDepthTest(); RenderSystem.depthMask(false); RenderSystem.enableBlend(); RenderSystem.blendFuncSeparate(SourceFactor.ONE, DestFactor.ONE, SourceFactor.ONE, DestFactor.ONE); p_282460_.setColor(f1, f2, f3, 1.0F); p_282460_.blit(NAUSEA_LOCATION, 0, 0, -90, 0.0F, 0.0F, i, j, i, j); p_282460_.setColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.defaultBlendFunc(); RenderSystem.disableBlend(); RenderSystem.depthMask(true); RenderSystem.enableDepthTest(); p_282460_.pose().popPose(); }   Note: Most of this is directly copied from GameRenderer as you pointed out you found. The only thing you'll have to likely do is update the `oSpinningEffectIntensity` + `spinningEffectIntensity` variables on the player when your effect is applied. Which values should be there? Not 100% sure, might be a game of guess and check, but `handleNetherPortalClient` in LocalPlayer has some hard coded you might be able to start with.
    • 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
  • Topics

×
×
  • Create New...

Important Information

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