Getting the normal with dFdx and dFdy

Hello,

I cant understand this way of get the normals. Let me show you a bit of code:

In vertex shader…

fragVertexEc = (_mv * vec4(vertex, 1.0)).xyz;
(_mv is the uniform mat4 modelView Matrix)

In fragment shader…

vec3 X = dFdx(fragVertexEc);
vec3 Y = dFdy(fragVertexEc);
vec3 normal=normalize(cross(X,Y));

what are doing here dFdx and dFdy gsgl commands?

Thanks

dFdx and dFdy return approximations to the derivatives of their arguments. Applying them to a position on a surface returns a tangent to that surface. As the cross-product of two vectors is perpendicular to both vectors, the cross-product of two tangents is normal to the surface.

However, because fragVertexEc is linearly interpolated across the triangle, the derivatives should be the same for all fragments, so performing the calculation for each fragment is inefficient.

Thanks for your response…To be more efficient…Could I calculate fragVertexEc in vertex shader and pass the result to the fragment shader?

Could I calculate fragVertexEc in vertex shader and pass the result to the fragment shader?

Your code is already doing that.

To be more efficient, you’d calculate the normal in the geometry shader, then pass it to the fragment shader using a flat-qualified output, e.g. “flat out vec3 normal”.

If you wanted smooth shading, you’d calculate the normal for each vertex in the vertex shader then to the fragment shader using an unqualified output, e.g. “out vec3 normal”. Note that you need to re-normalise the normal in the fragment shader.

To be more efficient, you’d calculate the normal in the geometry shader, then pass it to the fragment shader using a flat-qualified output, e.g. “flat out vec3 normal”.

Unless of course the usual inefficiency associated with using a GS at all hurts more than a cross-product in the FS. That probably depends on how many fragments you’re generating.

I found an interesting article explaining this topic

http://athile.net/library/blog/?tag=dfdx

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.