adrianton3
adrianton3

Reputation: 2358

Understanding fragments

I've just started working with fragment shaders and after I've done some simple plasma effects I got stuck. I already know that you can retrieve a fragment's X, Y and Z and I was thinking of building a shader that will colour fragments according to their Z.

Here's what I have so far:

void main() {
    float z = gl_FragCoord.z;
    float t = (sin(z) + 1) * 0.5;

    gl_FragColor = vec4(t, t, t, 1);
}

The problem is that I'm testing this with a triangle and no matter how I rotate it, it has the same constant colour so I'm starting to ask myself (and on SO): Why is the triangle of one single colour? Isn't this Z supposed to be per fragment?

Upvotes: 1

Views: 156

Answers (1)

Mortennobel
Mortennobel

Reputation: 3481

The z coordinate in the gl_FragCoord is normalised between 0 and 1 (where 0 correspond to the near-plane and the 1 correspond to the far-plane). Using perspective projection, this mapping is non-linear in favour of the near-plane. This means that it is likely that your triangle will map to the same color even when rotated.

It is worth pointing out that your general idea works just fine (created in my GLSL shader editor): http://goo.gl/32Voo

Note that I here use orthogonale projection to get a better depth visualisation - switching to projection makes the color almost identical (only varies a few percentage).

Upvotes: 2

Related Questions