Skip to main content

random: Deterministic Pseudo-Random Generation

High-Quality Hash Functions for Procedural Randomness

Pseudo-random generators create deterministic yet unpredictable values from input coordinates. These functions transform spatial coordinates into seemingly random distributions through mathematical hash operations, enabling reproducible stochastic patterns.

Mathematical Foundation

The implementation uses polynomial hash functions with large prime multipliers to achieve uniform distribution:

random(x)=fract(sin(xc)s)\text{random}(x) = \text{fract}(\sin(x \cdot c) \cdot s)

Where cc represents coordinate mixing coefficients and ss is a large scaling factor (43758.5453) that amplifies small differences in the sine function.

For multi-dimensional inputs, dot products combine coordinates:

random(p)=fract(sin(pc)s)\text{random}(\vec{p}) = \text{fract}(\sin(\vec{p} \cdot \vec{c}) \cdot s)

Function Variants

FunctionInputOutputPurpose
randomfloatfloat1D scalar random
randomVec2vec2float2D position to scalar
randomVec3vec3float3D position to scalar
randomVec4vec4float4D position to scalar
random2Floatfloatvec21D to 2D vector random
random3Vec2vec2vec32D to 3D vector random
random4Vec3vec3vec43D to 4D vector random

Implementation

Live Editor
const fragment = () => {
      const p = uv.mul(20).floor()
      const r = randomVec2(p)
      const cellColor = random3Vec2(p).mul(0.5).add(0.5)
      const noise = r.step(0.7)
      return vec4(cellColor.mul(noise), 1)
}
Live Editor
const fragment = () => {
      const scale = 8
      const coord = uv.mul(scale).floor()
      const rnd = random4Vec2(coord)
      const pattern = rnd.x.mul(rnd.y).mul(rnd.z).step(0.3)
      const hue = randomVec2(coord.add(vec2(100)))
      const color = vec3(pattern.mul(hue))
      return vec4(color, pattern)
}