randomhlsldirectx-9pixel-shader

Can I generate a random number inside a pixel shader?


I'm trying to write a very simple shader that adds random sparkle to applicable objects. The way I'd like to do this is by adding a random shade of white (R = G = B) to the pixel value within the pixel shader.

It seems that noise() doesn't work the way I hope it does:

float multiplier = noise(float3(Input.Position[0], Input.Position[1], time));

It gives me "error X4532: cannot map expression to pixel shader instruction set" referring to the call to noise().

Since I don't know of a way to retain a number between calls to the shader, I don't think I can just write a simple random number producing function based on a seed passed in before rendering.

Is there a way to produce a random number from inside a pixel shader? If there is a way, how?


Solution

  • There's nothing that says you have to reuse the seed for a random generator from run to run, you just need any seed.

    If you use, say, the pixel coordinate, then you will end up with a deterministic result (i.e. pixel x, y will always have the same random flare to it), but overall the entire face it will be randomly distributed.

    Now, if you have available as input something that changes based on the environment (I don't really know anything about pixel shaders), like the overall placement of the pixel in the global space of the scene/camera combination than relative to the polygon itself, then, especially in a fast moving environment, your results will effectively random.

    If everything in the global environment happens to be exactly the same, then, yes, you will have the exact same "random" distribution. But it any of those factors change (notably based on user input, which it likely you most dynamic "noise source") then overall the effect will be, likely, "random enough".

    So, the key take away is that your seed does not have to be the result of a previous run of the random number generator. It can be anything. So, contriving a seed for each pixel based on inputs to the shader to your own RNG may give you the effect you need.