Search code examples
openglglslshader

GLSL cubemap reflection shader


I'm developing OpenGL application and having problem implementing cubemap reflection shader: reflection rotates with camera around the object, it's is same from any point of view.

Here is my vertex shader:

in vec4 in_Position;
in vec4 in_Normal;

out vec3 ws_coords;
out vec3 normal;

mat4 uniform_ModelViewProjectionMatrix;
mat4 uniform_ModelViewMatrix;
mat4 uniform_ModelMatrix;
mat3 uniform_NormalMatrix;
vec3 uniform_CameraPosition;
...
ws_coords = (uniform_ModelViewMatrix * in_Position).xyz;
normal = normalize(uniform_NormalMatrix * in_Normal);

And fragment:

uniform samplerCube uniform_ReflectionTexture;
...
vec3 normal = normalize(normal);    
vec3 reflectedDirection = reflect(normalize(ws_coords), normal);
frag_Color = texture(uniform_ReflectionTexture, reflectedDirection).xyz

All shaders I found over the internet have same issue or producing weird results for me.

I guess I need to rotate reflected direction with camera rotation but I have no idea how can I do that. On shader input I have world space camera position, MVP, MV, M and Normal matrices.

Can you please help me implementing shader, that takes in account camera direction.


Solution

  • This part seems a bit odd to me:

    vec3 reflectedDirection = reflect(normalize(ws_coords), normal);
    

    The first argument to reflect has to be a vector that goes from the pixel position to the camera position, in world space.

    I suggest you have a camera world position, then take your in_Position to world space (I don't know which space they're currently in) and create a normalized vector from that. Then reflect it with a world space normal vector and sample your cubemap.