PDA

View Full Version : Lighting during rotation of object



Łukasz
04-20-2017, 04:46 AM
Hi,

I try to add diffuse light while rotation of cube. Everything works almost perfectly. Unfortunately lighting on sides closer to source of light had bad shadow appearing. For example from left to right instead from right to left while spinning around. So I created ugly workaround in my shader and it helps. Please, help me to find the solution of this problem.


vertexShader =
"attribute vec3 position;\n"
"attribute vec4 sourceColour;\n"
"attribute vec2 textureCoordIn;\n"
"attribute vec3 normal;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 model;\n"
"uniform mat4 viewMatrix;\n"
"\n"
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"varying vec3 normalOut;\n"
"varying vec3 positionOut;\n"
"\n"
"void main()\n"
"{\n"
" vec3 lightPos = vec3(1.0, 0.3, 2.0); \n"
" if(sign(normal.y) != sign(lightPos.y) && normal.y != 0) {\n" // workaround
" positionOut = -position;\n" // workaround
" }\n"
" else if(sign(normal.z) != sign(lightPos.z) && normal.z != 0) {\n" // workaround
" positionOut = -position;\n" // workaround
" }\n"
" else {\n"
" positionOut = position;\n"
" }\n"
" normalOut = normal * mat3(projectionMatrix * viewMatrix);\n"
" destinationColour = sourceColour;\n"
" textureCoordOut = textureCoordIn; \n"
" gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0f);\n"
"}\n";

fragmentShader =

"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"varying vec3 normalOut;\n"
"varying vec3 positionOut;\n"
"\n"
"uniform sampler2D tex;\n"
"\n"
"vec3 lightPos = vec3(1.0, 0.3, 2.0);\n"
"vec3 lightColor = vec3(1.0, 1.0, 1.0);\n"
"\n"
"void main()\n"
"{\n"
" // Diffuse \n"
" vec3 norm = normalize(normalOut);\n"
" vec3 lightDir = normalize(lightPos - positionOut);\n"
" float diff = max(dot(norm, lightDir), 0.0);\n"
" vec3 diffuse = diff * lightColor;\n"
"\n"
" vec3 result = (vec3(0.1, 0.1, 0.1) + diffuse) * texture2D(tex, textureCoordOut);"
" gl_FragColor = vec4(result, 1.0f) ; \n" //* destinationColour; \n"
"}\n";