Skip to content

Instantly share code, notes, and snippets.

@JuanDiegoMontoya
Last active March 21, 2024 03:59
Show Gist options
  • Save JuanDiegoMontoya/f4226d0fa3c627bb78e82fda67057d6e to your computer and use it in GitHub Desktop.
Save JuanDiegoMontoya/f4226d0fa3c627bb78e82fda67057d6e to your computer and use it in GitHub Desktop.
A fast, robust, and easy-to-use set of functions for generating random numbers in GLSL. Rehosted/stolen from here so it's in an easier-to-access location: https://www.shadertoy.com/view/sd3GR2
// PCG hash, see:
// https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/
// Used as initial seed to the PRNG.
uint pcg_hash(uint seed)
{
uint state = seed * 747796405u + 2891336453u;
uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
return (word >> 22u) ^ word;
}
// Used to advance the PCG state.
uint rand_pcg(inout uint rng_state)
{
uint state = rng_state;
rng_state = rng_state * 747796405u + 2891336453u;
uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
return (word >> 22u) ^ word;
}
// Advances the prng state and returns the corresponding random float.
float rand(inout uint state)
{
uint x = rand_pcg(state);
state = x;
return float(x)*uintBitsToFloat(0x2f800004u);
}
uniform uint u_viewportWidth;
layout(location = 0) out vec3 fragColor;
void main()
{
uvec2 ucoord = uvec2(gl_FragCoord.xy);
uint pixel_index = ucoord.x + ucoord.y * uint(u_viewportWidth);
uint seed = pcg_hash(pixel_index);
// a random vec3 in [0, 1]
fragColor = vec3(rand(seed), rand(seed), rand(seed));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment