Hello,
Please, take a look at this: How to get the viewing angle relative to the normal in a GLSL fragment shader? - Stack Overflow. It has even a browser-runnable example in WebGL.
GLSL code for the vertex shader (the shader in which you can do geometry computations). Notice the out
modifier of the viewNV
vector, signaling you want to communicate it to other shaders down the rendering pipeline:
in vec3 inPos;
in vec3 inNV;
out vec3 viewNV;
uniform mat4 u_projectionMat44;
uniform mat4 u_viewMat44;
uniform mat4 u_modelMat44;
void main()
{
viewNV = mat3(u_viewMat44 * u_modelMat44) * inNV;
vec4 pos = u_viewMat44 * u_modelMat44 * vec4( inPos, 1.0 );
gl_Position = u_projectionMat44 * pos;
}
You actually need only the viewNV
information, but writing to the built-in gl_Position
variable is required in order to have a valid vertex shader.
Next, here’s the GLSL code for the fragment (pixel) shader (the shader where you can calculate the pixel color). Notice it receives the viewNV
vector (the in
modifier) previously computed in the vertex shader:
in vec3 viewNV;
void main()
{
vec3 N = normalize(viewNV);
vec3 L = vec3(0.0, 0.0, 1.0);
float NdotL = dot(N, L);
vec3 color = vec3(NdotL, 0.0, 1.0-NdotL);
gl_FragColor = vec4( color.rgb, 1.0 );
}
The fragment shader above will give redder hues for pixels of faces facing the camera and more violet hues for faces more edge-on.
I hope this helps,
PC