Search code examples
typescriptwebgpuwgsl

How to use a random number within WGSL?


I'm trying to create a fragment shader in a WebGPU application for rendering a black white image noise.

White_noise (wikipedia)

For this I just want each pixel to have a random color value like this:

[[stage(fragment)]]
fn main() -> [[location(0)]] vec4<f32> {
  let color: f32 = random();
  return vec4<f32>(color, color, color, 1.0);
}

But WGSL does not seem to provide a function that returns random numbers. At least I could not find anything in the specifications.

Is there a way to get random numbers into the fragment shader for each fragment?


Solution

  • There is no random functionality in WGSL or GLSL, so you have to implement your own RNG. There are different approaches to implement it either via CPU generated numbers and feed into the shader via an uniform or via algorithm within the shader, as @skmr has described.

    On possible algorithm could be: https://indico.cern.ch/event/93877/contributions/2118070/attachments/1104200/1575343/acat3_revised_final.pdf