Jump to content

Recommended Posts

Posted

Heyy,

 

in every recent version of Forge I've looked at, the #hashCode() method for BlockPos is overwritten in Vec3i as follows:

public int hashCode()
{
	return (this.getY() + this.getZ() * 31) * 31 + this.getX();
}

(Credit to Mojang or the Forge Team)

 

This would result in duplicate hashes for many positions. Technically there are only 31k positions which this could represent. Positions like (31 | 0 | 0) and (0 | 1 | 0) have the same hash code.

 

Is this something that is just overlooked in mods today or is there a safe implementation for hashing BlockPos's?

 

Let's say for example I have some type of structure that is 32 x 32 x 32 blocks big and I want to store something in a HashMap as in HashMap<BlockPos, Block>. This would lead to errors because of the duplicate hash I mentioned above.

Posted (edited)

not sure if this is related but in BlockSnapshot

    @Override
    public int hashCode()
    {
        int hash = 7;
        hash = 73 * hash + this.getMeta();
        hash = 73 * hash + this.getDimId();
        hash = 73 * hash + this.getPos().hashCode();
        hash = 73 * hash + this.getRegistryName().hashCode();
        hash = 73 * hash + Objects.hashCode(this.getNbt());
        return hash;
    }

maybe it is not used directly?

Edited by poopoodice
Posted

Hash codes are explicitly NOT guaranteed unique. that's why equals exists and is tied to hashCode.

 

think about it, how would you shove 96 bits of information (3 ints) into 32 bits (1 int) hash code uniquely? literally impossible. 

 

The standard practice is to try and spread out the hash codes when you can to spread out the collisions. Which is typically implemented by multiplying intermediate hash codes by some prime number. In this case 31.

 

And no there is not 31k possible values for a vec3i hash code. there are 2^32 possibilities. 

I do Forge for free, however the servers to run it arn't free, so anything is appreciated.
Consider supporting the team on Patreon

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

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