WCG MV

Saturday, March 17, 2007

HLSL Tips 1: Pseudo-random Number Generator

Preface
PRNG on the GPU. Two pseudo random numbers per iteration (from the BA channels). Inspired by Pete Warden's fragment program for pseudo-random number generation. In turn based on an algorithm described by Francois Grieu, sci.crypt, 5th February 2004. Implementd in Cg by Alex Campbell. 7th August 2006. Thanks for their works. I implement it in HLSL now.
Function
#define cMult 0.0001002707309736288
#define aSubtract 0.2727272727272727
float4 randGrieu(float4 t)
{
float a=t.x+t.z*cMult+aSubtract-floor(t.x);
a*=a;
float b=t.y+a;
b-=floor(b);
float c=t.z+b;
c-=floor(c);
float d=c;
a+=c*cMult+aSubtract-floor(a);
a*=a;
b+=a;
b-=floor(b);
c+=b;
c-=floor(c);
return float4(a,b,c,d);
}
Application
Code snippet:
float4 color=tex2D(TextureSampler, In.TexCoord0);
color=randGrieu(color);
Out.color=color;

The original texture is as follows:


After called randGrieu() once, the result texture is:

1 comment:

Anonymous said...

Hi, good to see this
I'm interested in getting randomness into HLSL while avoiding generating noise textures. So this is very useful

thanks