4

A Simple Hash for Perlin Noise

 2 years ago
source link: https://marcospereira.me/a-simple-hash-for-perlin-noise/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A Simple Hash for Perlin Noise

I needed a hashing algorithm that is simple to implement and quick to compute, to be used as a basis for generating perlin noise in Unity.

I couldn’t rely on simple randomness since terrain generation has to be deterministic, especially for multiplayer games.

I ended up implementing the Fowler–Noll–Vo 1a hash, which is known for trading some quality for increased performance. It was designed to be fast, not secure - which is exactly what is needed in the context of procedural generation.

Let me first show you what it looks like. You can use the DebugTexture() method to get a sample texture, which is generated by hashing the coordinates of each pixel and mapping that hash to a color between black and white:

Hash with tricks

I used a couple tricks to get the hash to look as close as possible to white noise when passing in sequential numbers starting from 0 or near 0.

The first trick is to multiply each coordinate by one of the algorithm’s parameters (the prime number), which gets the bits away from being almost all 0s when hashing low values.

The second trick is to hash the bytes in a random sequence. This sequence is hardcoded for simplicity.

Without these two tricks, the hash looks much less like pure white noise. This is the result if we hash the coordinates as floating point numbers, using no tricks:

Hash without tricks from floats

And this if we hash coordinates as integers, also with no tricks:

Hash without tricks from integers

The full source code is below:

Written on May 10, 2022

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK