Jump to content

Recommended Posts

Posted

I'm looking for a way to record a block owner (as in, the player who placed the block). I already have a tile entity attached to the block.

 

I am mainly interested in the most efficient way to store this info, compare it to players interacting with the block, and saving it to NBT.

 

Does anybody have any suggestions?

Posted

Are wa talking about one type of your block with tile entity? Or maybe you want to sign other/vanilla blocks?

 

Well, anyway: You want to hold UUID in your TE and save it to NBT. UUID can be written as 2 longs (lookup vanilla examples where uuid is saved/loaded).

 

Then based on loaded UUID you can retrieve EntityPlayer on server. Note that you can (should) find (by uuid) that player once and save it in WeakReference<EntityPlayer>. If you need player on client (display) - you need to ask yourself - how much data do you need to show, you can e.g send only name or whole reference (using entityId and World#getEntityById()).

 

If you want to save such data for other blocks - well, you need to take different approach (still saving using UUIDs and probably NBT) but using some per-world position maps.

1.7.10 is no longer supported by forge, you are on your own.

Posted

Entity#getUniqueID()

 

UUID#getLeastSignificantBits()

UUID#getMostSignificantBits()

 

NBT#setLong("L", least)

NBT#setLong("M", most)

 

new UUID(NBT#getLong("L"), NBT#getLong("M"))

 

if (player ref not present) do:

WeakReference<EntityPlayer> player = World#getPlayerEntityByUUID(UUID)

else return player.get()

 

What else...

Again - DO YOU NEED client to know about player held by TE? Know = display.

Because "as well as which GUI to display on right-click." can be done from server, client doesn't need player there.

1.7.10 is no longer supported by forge, you are on your own.

Posted

A couple months ago I invented a pressure plate that would be owned (breakable and usable) by the player who places it. This is the class I wrote to implement weak pointer references:

 

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.UUID;

import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;

/**
* Usage notes:
* 
* 1) When the ownable object first becomes owned, it should call setOwner.
* 
* 2) Classes employing WeakOwner must Override read and write NBT to call WeakOwner's.
* 
* 3) Whenever you need the player, use getOwnerEntity. It will return null if the player is not online.
*/
public class WeakOwner {

  private WeakReference<EntityPlayer> ownerEntity;
  private UUID ownerID;

  public void setOwner(EntityLivingBase owner) {    // The definitive moment when owner is known a-priori
    this.ownerID = owner.getUniqueID ();

    if (! (owner instanceof EntityPlayer)) {        // Awkwardly, Block's onBlockPlacedBy method gives us a livingBase
      this.ownerEntity = new WeakReference (null);  // And we must instantiate our private fields at all costs
      System.out.println ("Owner set by non-player entity!");
    }
    this.ownerEntity = new WeakReference ((EntityPlayer) owner);
  }

  public EntityPlayer getOwnerEntity() {
    EntityPlayer owner = ownerEntity.get ();        // See what entity we already know
    if (owner == null || owner.isDead) {            // If useless,
      owner = lookupOwner ();                       // Try to find it
    }
    return owner;                                   // WARNING: May still be null (not logged in)
  }

  public UUID getOwnerID() {
    return ownerID;
  }

  public EntityPlayer lookupOwner() {
    if (ownerID == null) return null;
    List<EntityPlayerMP> allPlayers = MinecraftServer.getServer ().getConfigurationManager ().playerEntityList;
    for (EntityPlayerMP p : allPlayers) {
      if (p.getUniqueID ().equals (ownerID)) {
        setOwner (p);
        return ownerEntity.get ();
      }
    }
    return null;
  }

  public void readFromNBT(NBTTagCompound compound) {    // Read two longs into the UUID, not used until needed
    ownerID = new UUID (compound.getLong ("UUIDMost"), compound.getLong ("UUIDLeast"));
    ownerEntity = new WeakReference (lookupOwner ());
  }

  public void writeToNBT(NBTTagCompound compound) {     // Write owner's UUID to two longs, in order needed at read
    if (null == ownerID) return;
    compound.setLong ("UUIDMost", ownerID.getMostSignificantBits ());
    compound.setLong ("UUIDLeast", ownerID.getLeastSignificantBits ());
  }

}

 

Here's part of the p-plate class:

  /**
   * Owner may invert the detection from self to everyone else.
   */
  @Override
  public boolean onBlockActivated(World w, BlockPos pos, IBlockState state, EntityPlayer p, EnumFacing side, float hitX, float hitY, float hitZ) {
    TileEntity te = w.getTileEntity (pos);

    if (te instanceof classTEOwnerPlate) {
      classTEOwnerPlate smarte = (classTEOwnerPlate) te;
      if (smarte.toggle (p)) {
        w.playSoundEffect (smarte.x (), smarte.y (), smarte.z (), "dig.snow", 1.0F, smarte.isInverted () ? 1.0F : 0.2F);
        te.markDirty ();
        return true;
      }
    }
    return false;
  }

  /**
   *    The only function here is to set owner in our tile entity. If we can't do that, then bad things will happen. 
   */
  @Override
  public void onBlockPlacedBy(World w, BlockPos pos, IBlockState state, EntityLivingBase elb, ItemStack stack) {
    super.onBlockPlacedBy (w, pos, state, elb, stack);          // For now, a no-op, but who knows?

    TileEntity te = w.getTileEntity (pos);

    if (te == null) {
      System.out.println ("Failed to get TE!");
      return;
    }

    if (! (te.getBlockType ().getClass () == this.getClass ())) {
      System.out.println ("TE is for wrong block: " + te.getBlockType ().getUnlocalizedName ());
      return;
    }
    ((classTEOwnerPlate) te).setOwner (elb);
  }

 

and part of the TE class:

  public void readFromNBT(NBTTagCompound compound) {    // NBT tells us who placed us originally
    super.readFromNBT (compound);
    this.inverted = compound.getBoolean ("inverted");
    this.owner.readFromNBT (compound);
  }

  public void writeToNBT(NBTTagCompound compound) {
    super.writeToNBT (compound);
    compound.setBoolean ("inverted", this.inverted);
    this.owner.writeToNBT (compound);
  }

 

As you can see, I added the concept of "inverted" that you probably don't need, so ignore that. You should be able to connect the dots from here.

 

Also, if you're unfamiliar with weak references (as I was when I started), look up an article on them.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

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

    • So, I have a minecraft world hosted with essential on forge 1.20.1, there's 149 mods, and the forge version is 47.3.0, and it's been like that for a good 2-3 weeks, and all of a sudden, it stopped loading, and I have 0 clue as to why, and this world means A LOT to me, so if anyone out there is able to help, I would GLADLY appreciate it. here's the link if ya wanna help:   [04Dec2024 22:42:24.552] [Worker-ResourceReload-3/ERROR][net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener/]: Couldn't parse data file slabsexpanded:snow_blockblocktoslab from slabsexpanded:recipes/snow_blockblocktoslab.json com.google.gson.JsonParseException: com.google.gson.stream.MalformedJsonException: Expected name at line 16 column 4 path $.result.item at net.minecraft.util.GsonHelper.m_13780_(GsonHelper.java:526) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at net.minecraft.util.GsonHelper.m_263475_(GsonHelper.java:531) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at net.minecraft.util.GsonHelper.m_13776_(GsonHelper.java:581) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener.m_278771_(SimpleJsonResourceReloadListener.java:41) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener.m_5944_(SimpleJsonResourceReloadListener.java:29) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener.m_5944_(SimpleJsonResourceReloadListener.java:17) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at net.minecraft.server.packs.resources.SimplePreparableReloadListener.m_10786_(SimplePreparableReloadListener.java:11) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?] at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768) ~[?:?] at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1760) ~[?:?] at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:373) ~[?:?] at java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1182) ~[?:?] at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1655) ~[?:?] at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1622) ~[?:?] at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:165) ~[?:?] Caused by: com.google.gson.stream.MalformedJsonException: Expected name at line 16 column 4 path $.result.item at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1657) ~[gson-2.10.jar%23107!/:?] at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:514) ~[gson-2.10.jar%23107!/:?] at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:422) ~[gson-2.10.jar%23107!/:?] at com.google.gson.internal.bind.TypeAdapters$28.read(TypeAdapters.java:779) ~[gson-2.10.jar%23107!/:?] at com.google.gson.internal.bind.TypeAdapters$28.read(TypeAdapters.java:725) ~[gson-2.10.jar%23107!/:?] at com.google.gson.internal.bind.TypeAdapters$34$1.read(TypeAdapters.java:1007) ~[gson-2.10.jar%23107!/:?] at net.minecraft.util.GsonHelper.m_13780_(GsonHelper.java:524) ~[client-1.20.1-20230612.114412-srg.jar%23490!/:?]
    • Hello! I have been having a problem with Forgematica, Embeddium, Oculus, and create. I wanted to download litematica so I could see which blocks are in my creative mode build, so that I could collect them all in survival. However, litematica is a fabric mod. I found a port called forgematica, which I added (along with it's dependency) to my mods folder. I loaded into a new world, and built a structure. Then, I added a part from the create mod, and the game crashed instantly, with exit code -1. Thanks for any help! Crash Report and mods list: https://pastebin.com/rtzh6LAi
    • Have you found a modder for this vehicle project? Because it will be really hard and I want to know that hero who can create all this
  • Topics

  • Who's Online (See full list)

    • There are no registered users currently online
×
×
  • Create New...

Important Information

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