Sign in to follow this  

Proper cubemapped reflections with GLSL

Recommended Posts

Hello, I have been experimenting with cubemapped reflections and I got them to work properly with the fixed pipeline, mainly thanks to the NVidia papers. But when I try to move that piece of code to a shader... the cubemapped reflection rotates with my view. Free Image Hosting at Free Image Hosting at In the fixed pipeline, I got rid of this with the texture matrix trick:

But now I don't know how to rotate the cube map texture matrix in the shader. This is the code for the vertex shader:
varying vec3 SurfaceNormal;
varying vec3 ReflectVector;

void main()
	gl_Position = ftransform();
	gl_TexCoord[0] = gl_MultiTexCoord0;
	gl_TexCoord[1] = gl_MultiTexCoord1;
	SurfaceNormal = normalize(gl_NormalMatrix * gl_Normal);
	vec4 Position = gl_ModelViewMatrix * gl_Vertex;
	ReflectVector = reflect(, SurfaceNormal);
And the fragment shader:
uniform sampler2D Texturemap;
uniform sampler2D Normalmap;
uniform samplerCube Cubemap;

varying vec3 SurfaceNormal;
varying vec3 ReflectVector;

void CalcLight(in int Light, inout vec4 AmbientColor, inout vec4 DiffuseColor, inout vec4 SpecularColor)
	float nDotVP;
	float nDotHV;
	float pf;
	nDotVP = max(0.0, dot(SurfaceNormal, normalize(vec3(gl_LightSource[Light].position))));
	nDotHV = max(0.0, dot(SurfaceNormal, vec3(gl_LightSource[Light].halfVector)));
	if (nDotVP == 0.0)
		pf = 0.0;
		pf = pow(nDotHV, 1000.0);
	AmbientColor += gl_LightSource[Light].ambient;
	DiffuseColor += gl_LightSource[Light].diffuse * nDotVP;
	SpecularColor += gl_LightSource[Light].specular * pf;

void main()
	vec3 BaseColor = vec3(texture2D(Texturemap,gl_TexCoord[0].st));
	vec4 GlossMap = vec4(texture2D(Normalmap,gl_TexCoord[1].st));

	vec3 EnvColor = vec3(textureCube(Cubemap, ReflectVector));
	EnvColor *= EnvColor;
	vec3 Tint = vec3(0.6,0.6,0.6);
	EnvColor *= Tint;

	vec4 AmbientColor, DiffuseColor, SpecularColor;
	CalcLight(0, AmbientColor, DiffuseColor, SpecularColor);
	CalcLight(1, AmbientColor, DiffuseColor, SpecularColor);
	CalcLight(2, AmbientColor, DiffuseColor, SpecularColor);
	gl_FragColor = vec4(EnvColor, 1.0)*(AmbientColor+DiffuseColor+SpecularColor);
So I'm reflecting the view vector and blah blah blah, but I have no idea on how to take account of the view rotation. I know I'm missing the stupidest thing, but somehow I can't solve it :/

Share this post

Link to post
Share on other sites
Update the texture matrix in cpu code as normal, then in glsl transform your position variable with gl_TextureMatrix.

Unless I'm missing something it should be that simple.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this