Rotate Normals in Shader

爷,独闯天下 提交于 2019-12-04 08:13:03

You do need to transform the normals, by the upper 3 rows/cols of the model-view-projection matrix. (If you are performing any scaling though, you need to use the inverse transpose of this matrix. See this article).

mat3 normalMatrix = mat3(mvp);
normalMatrix = inverse(normalMatrix);
normalMatrix = transpose(normalMatrix);
f_normal = normalize(normal * normalMatrix);
// You should also send your tranformed position to the fragment shader
f_position = vec3(mvp * vec4(position, 1.0));

In your fragment shader, you need to calculate the distance from your light source to your fragment and normalize. Find the dot product of the normal and the light vector and multiply this by the light color.

vec3 light = normalize(sun - f_position);
light = max(dot(f_normal, light), 0.0) * vec3(1.0, 1.0, 1.0);
gl_FragColor = texture(tex, f_texcoord) * vec4(light, 1.0);

There is definitely room for optimization in my code.

I recommend this book OpenGL 4.0 Shading Language Cookbook.

The following solution works with my models, but I don't have a very deep understanding of the maths behind it. This is my source: Adding Depth and Realism - Surface Normals

The transform you need to apply to your normal vectors is denoted by: N' = N * (M-1)T

Basically, this means that you multiply your normals (N) by the inverse-transpose of your ModelView matrix (M). If your M matrix is 4x4, you should just use the resulting 3x3 upper-left quadrant of (M-1)T for the normal multiplication.

Again, this works for me but I can't explain the maths too well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!