Drawing a sphere using shader

From author of Molecules - SO / Molecules v1

see also

caption

shadertoy code

vec3 lightPosition = vec3(0.5, 0.5, 0.5);
uniform mediump float sphereRadius;
vec3 sphereColor = vec3(1.0, 0.0, 0.0);

mediump vec3 normalizedViewCoordinate;

void sphere(out vec4 fragColor, in vec2 impostorSpaceCoordinate)
{
    float distanceFromCenter = length(impostorSpaceCoordinate);

    // Establish the visual bounds of the sphere
    if (distanceFromCenter > 1.0)
    {
        discard;
    }

    float normalizedDepth = sqrt(1.0 - distanceFromCenter * distanceFromCenter);

    // Current depth
    float depthOfFragment = sphereRadius * 0.5 * normalizedDepth;
    //        float currentDepthValue = normalizedViewCoordinate.z - depthOfFragment - 0.0025;
    float currentDepthValue = (normalizedViewCoordinate.z - depthOfFragment - 0.0025);

    // Calculate the lighting normal for the sphere
    vec3 normal = vec3(impostorSpaceCoordinate, normalizedDepth);

    vec3 finalSphereColor = sphereColor;

    // ambient
    float lightingIntensity = 0.3 + 0.7 * clamp(dot(lightPosition, normal), 0.0, 1.0);
    finalSphereColor *= lightingIntensity;

    // Per fragment specular lighting
    lightingIntensity  = clamp(dot(lightPosition, normal), 0.0, 1.0);
    lightingIntensity  = pow(lightingIntensity, 60.0);
    finalSphereColor += vec3(0.4, 0.4, 0.4) * lightingIntensity;

    fragColor = vec4(finalSphereColor, 1.0);
}


void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = (2.0*fragCoord/iResolution.xy) + vec2( -1.0, -1.0);
    sphere( fragColor, uv);
}
Written on May 27, 2018, Last update on June 4, 2024
shader sphere