I don’t see how you can set gl_FragDepth with values contained in gl_Position:
[ul][li]gl_FragDepth is in the output of a fragment shader (section Shader Inputs, spec 2.1 page 198) , whereas gl_Position is in the output of a vertex shader (section Varying Variables, spec 2.1 page 84).[*]The input of a fragment shader is gl_FragCoord which is very different from what gl_Position is.[/ul][/li]
Syntaxically, your code should not even compile.
Look what happen to gl_Position (see 2.15.4 Shader Execution, “The following operations are applied to vertex values that are the result of executing the vertex shader”,spec 2.1 page 85):
gl_Position contains the clip coordinates of a vertex. Let’s note these coordinates (x_c,y_c,z_z,w_c). It means gl_Position.xyzw=(x_c,y_c,z_c,w_c).
[ul][li]1 The perspective division divides the clip coordinates by w_c, and gives the normalized device coordinates (x_d,y_d,z_d)[*]2 the viewport transformation followed by an optional polygon depth offset is applied. The result of this transformation are the window coordinates of the vertex (x_w,y_w,z_w)[/li]
This is the notation of section 2.11.1, spec 2.1, page 42.[/ul]
At this point we have the position of the vertex expressed in window coordinates.
I know that’s a lot of “w” with different meanings, and that’s why it is confusing:
[ul][li]_w: for a component expressed in window coordinates.w: for the fourth element of a vector in a shaderw_c: for the fourth component of vertex position expressed in clip coordinates.[/ul][/li]
It becomes nasty when it comes to the fourth element of the input of a fragment shader gl_FragCoord.w.
Now, what happens during the rasterization of some primitive.
Let’s take a simple line segment for the purpose of the discussion between vertices V0 and V1.
x_w and y_w are linearly interpolated between V0 and V1.
let’s note x_i and y_i these interpolated values.
z_w is linearly interpolated as well: (equation 3.7, spec 2.1, page 104)
see “Shader Inputs” (spec 2.1, page 198)
Finally, here is the really confusing notation: gl_FragCoord.w
It is not an interpolated value expressed in window coordinates, but the interpolated value of the invert of w_c, the fourth coordinate in clip coordinates.
Also, as Jan said, if you don’t write anything in gl_FragDepth, the value of gl_FragCoord.z is assigned to it automatically.
ref: Shader Ouputs, spec 2.1, page 199:
“If the active fragment shader does not statically assign a value to gl_FragDepth, then the depth value generated during rasterization is used by subsequent stages of the pipeline.”
I hope it will make you less confused about all the meanings of “w” and depth values.