Search code examples
glslshadersamplingfragment-shader

Finding point inside disk defined by a radius


I have come across a shader that I am trying to understand where a point is found within a disk defined by a radius.

How does this function DiskPoint work?

float HASHVALUE = 0.0f;
vec2 RandomHashValue()
{
    return fract(sin(vec2(HASHVALUE += 0.1, HASHVALUE += 0.1)) * vec2(43758.5453123, 22578.1459123));
}

vec2 DiskPoint(in float radius, in float x1, in float x2)
{
    float P = radius * sqrt(1.0f - x1);
    float theta = x2 * 2.0 * PI;
    return vec2(P * cos(theta), P * sin(theta));
}

void main()
{
    HASHVALUE = (uvCoords.x * uvCoords.y) * 64.0;
    HASHVALUE += fract(time) * 64.0f;

    for (int i = 0; i < samples; ++i)
    {
        vec2 hash = RandomHashValue();
        vec2 disk = DiskPoint(sampleRadius, hash.x, hash.y);
        //....
    }

}

Solution

  • I see it like this:

    vec2 DiskPoint(in float radius, in float x1, in float x2)
        {
        // x1,x2 are "uniform randoms" in range <0,+1>
        float P = radius * sqrt(1.0f - x1); // this will scale x1 into P with range <0,radius> but change the distribution to uniform number of points inside disc
        float theta = x2 * 2.0 * PI; // this will scale x2 to theta in range <0,6.28>
        return vec2(P * cos(theta), P * sin(theta)); // and this just use the above as polar coordinates with parametric circle equation ...
        // returning "random" point inside disc with uniform density ...
        }
    

    but I just guessed and not tested it so take that in mind