Trying to get the example code for CalcEyeFromWindow() (first one on the page) to work in WebGL, but having no luck.

Paired down the code to the following with some explicit values just in case something is amiss with parameter passing. Visualizing the output on a sphere of unit radius, centered in the view and 3 units from the camera. Using step() in the output to provide sharp color transitions on the sphere.

The current output is black. If I set the step to 0 for X and Y, the transitions for X and Y are centered on the sphere, so it would seem that the problem is at least in part due to the calculation of clipPos.w.

Vertex shader:

precision highp float;

attribute vec3 a_position;

uniform mat4 u_modelMatrix;
uniform mat4 u_viewMatrix;
uniform mat4 u_projectionMatrix;

void main()
    gl_Position = u_projectionMatrix * u_viewMatrix * u_modelMatrix * vec4(a_position, 1.0);

Fragment shader:

precision highp float;

uniform mat4 u_inverseProjectionMatrix;
uniform mat4 u_projectionMatrix;

vec3 CalcEyeFromWindow(void)
    vec3 ndcPos;
    // Hard code window-space position at gl_FragCoord
    // Hard code viewport dimensions
    ndcPos.xy = (2.0 * gl_FragCoord.xy) / vec2(1000, 500) - 1.;
    // Hard code clipping depths
    ndcPos.z = (2.0 * gl_FragCoord.z - 1. - 4.) / (4. - 1.);

    vec4 clipPos;
    clipPos.w = u_projectionMatrix[3][2] /
       (ndcPos.z - (u_projectionMatrix[2][2] / u_projectionMatrix[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;

    return (u_inverseProjectionMatrix * clipPos).xyz;

void main() {
    // Step to clarify position
    gl_FragColor = vec4(step(vec3(.5, .5, 2.2), CalcEyeFromWindow() *
         vec3(1,1,-1)), 1.);


The problem was that I had used the clip plane depths where I should have used the near and far values as passed to glDepthRange, which I now know are 0 and 1 by default. So, since I use these default values, the calculation of ndcPos.z should be:

ndcPos.z = (2.0 * gl_FragCoord.z - 0.0 - 1.0) / (1.0 - 0.0);

which can be simplified to:

ndcPos.z = 2.0 * gl_FragCoord.z - 1.0;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.