• Advertisement
Sign in to follow this  

OpenGL Shadow mapping using shaders

This topic is 2878 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, for the past week or so I've been trying to get shadow mapping to work, without much success. I'll get right to it and post the relevant bits of my code. It's a huge mess but it doesn't work yet.
#define CGLE() \	
{

	int error_codez2 = glGetError(); \
	if (error_codez2 > 0) \	{ \
		ERROR_OPENGL("%s (Error code: %i) at line %i in file %s.", gluErrorString(error_codez2), error_codez2, __LINE__, __FILE__); \
		
	} \
}

void Engine::Init()
{
	glGenBuffersARB				= (PFNGLGENBUFFERSARBPROC)				wglGetProcAddress("glGenBuffersARB");
	glBindBufferARB				= (PFNGLBINDBUFFERARBPROC)				wglGetProcAddress("glBindBufferARB");
	glBufferDataARB				= (PFNGLBUFFERDATAARBPROC)				wglGetProcAddress("glBufferDataARB");
	glBufferSubDataARB			= (PFNGLBUFFERSUBDATAARBPROC)			wglGetProcAddress("glBufferSubDataARB");
	glDeleteBuffersARB			= (PFNGLDELETEBUFFERSARBPROC)			wglGetProcAddress("glDeleteBuffersARB");

	// shadows

	glGenTextures(1, &s_ShadowTexture); CGLE();
	glBindTexture(GL_TEXTURE_2D, s_ShadowTexture); CGLE();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); CGLE();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); CGLE();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); CGLE();
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); CGLE();

	// enable shadow comparison
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE_ARB); CGLE();

	// if r <= texture
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); CGLE();

	// return an intensity
	glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); CGLE();

	const GLdouble x[] = {1.0, 0.0, 0.0, 0.0};
	const GLdouble y[] = {0.0, 1.0, 0.0, 0.0};
	const GLdouble z[] = {0.0, 0.0, 1.0, 0.0};
	const GLdouble w[] = {0.0, 0.0, 0.0, 1.0};

	glEnable(GL_TEXTURE_GEN_S); CGLE();
	glEnable(GL_TEXTURE_GEN_T); CGLE();
	glEnable(GL_TEXTURE_GEN_R); CGLE();
	glEnable(GL_TEXTURE_GEN_Q); CGLE();

	glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); CGLE();
	glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); CGLE();
	glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); CGLE();
	glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); CGLE();

	glTexGendv(GL_S, GL_EYE_PLANE, x); CGLE();
	glTexGendv(GL_T, GL_EYE_PLANE, y); CGLE();
	glTexGendv(GL_R, GL_EYE_PLANE, z); CGLE();
	glTexGendv(GL_Q, GL_EYE_PLANE, w); CGLE();

	glTexImage2D (
		GL_TEXTURE_2D,			// target
		0,						// level
		GL_DEPTH_COMPONENT,		// internal format
		g_ShadowWidth,			// width
		g_ShadowHeight,			// height
		0,						// border
		GL_DEPTH_COMPONENT,		// format
		GL_UNSIGNED_BYTE,		// type
		NULL					// pixels
	); CGLE();
	glBindTexture(GL_TEXTURE_2D, 0); CGLE();
}

void Engine::GenerateShadows()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CGLE();

	float pos[4] = { s_Lights[0]->GetPosition().x, s_Lights[0]->GetPosition().y, s_Lights[0]->GetPosition().z, 0 };

	glMatrixMode(GL_PROJECTION); CGLE();
	glLoadIdentity(); CGLE();
	gluPerspective(g_SpotAngle, 1.f, g_ShadowNear, g_ShadowFar); CGLE();
	glGetFloatv(GL_MODELVIEW_MATRIX, g_LightProjectionMatrix); CGLE();

	glMatrixMode(GL_MODELVIEW); CGLE();
	glLoadIdentity(); CGLE();
	gluLookAt (
		pos[0], pos[1], pos[2],
		0, 0, 0,
		0, 1, 0
	); CGLE();
	glGetFloatv(GL_MODELVIEW_MATRIX, g_LightModelMatrix); CGLE();

	float cam[16];

	glPushMatrix(); CGLE();
		glMatrixMode(GL_MODELVIEW); CGLE();
		glLoadIdentity(); CGLE();
		Project(); CGLE();
		glGetFloatv(GL_MODELVIEW_MATRIX, cam); CGLE();
	glPopMatrix(); CGLE();

	g_InverseCamera[0] = cam[0]; 
	g_InverseCamera[1] = cam[4]; 
	g_InverseCamera[2] = cam[8];
	g_InverseCamera[3] = 0.0f; 

	g_InverseCamera[4] = cam[1]; 
	g_InverseCamera[5] = cam[5]; 
	g_InverseCamera[6] = cam[9];
	g_InverseCamera[7] = 0.0f; 

	g_InverseCamera[8] = cam[2]; 
	g_InverseCamera[9] = cam[6]; 
	g_InverseCamera[10] = cam[10];
	g_InverseCamera[11] = 0.0f;

	g_InverseCamera[12] = 
		-(cam[12] * cam[0]) - 
		(cam[13] * cam[1]) - 
		(cam[14] * cam[2]);

	g_InverseCamera[13] = 
		-(cam[12] * cam[4]) - 
		(cam[13] * cam[5]) - 
		(cam[14] * cam[6]);

	g_InverseCamera[14] = 
		-(cam[12] * cam[8]) - 
		(cam[13] * cam[9]) - 
		(cam[14] * cam[10]);

	g_InverseCamera[15] = 1.0f;

	/*g_InverseCamera[0] = g_LightProjectionMatrix[0]; 
	g_InverseCamera[1] = g_LightProjectionMatrix[4]; 
	g_InverseCamera[2] = g_LightProjectionMatrix[8];

	g_InverseCamera[4] = g_LightProjectionMatrix[1]; 
	g_InverseCamera[5] = g_LightProjectionMatrix[5]; 
	g_InverseCamera[6] = g_LightProjectionMatrix[9];

	g_InverseCamera[8] = g_LightProjectionMatrix[2]; 
	g_InverseCamera[9] = g_LightProjectionMatrix[6]; 
	g_InverseCamera[10] = g_LightProjectionMatrix[10];

	g_InverseCamera[3] = 0.0f; 
	g_InverseCamera[7] = 0.0f; 
	g_InverseCamera[11] = 0.0f;
	g_InverseCamera[15] = 1.0f;

	g_InverseCamera[12] = 
		-(g_LightProjectionMatrix[12] * g_LightProjectionMatrix[0]) - 
		(g_LightProjectionMatrix[13] * g_LightProjectionMatrix[1]) - 
		(g_LightProjectionMatrix[14] * g_LightProjectionMatrix[2]);

	g_InverseCamera[13] = 
		-(g_LightProjectionMatrix[12] * g_LightProjectionMatrix[4]) - 
		(g_LightProjectionMatrix[13] * g_LightProjectionMatrix[5]) - 
		(g_LightProjectionMatrix[14] * g_LightProjectionMatrix[6]);

	g_InverseCamera[14] = 
		-(g_LightProjectionMatrix[12] * g_LightProjectionMatrix[8]) - 
		(g_LightProjectionMatrix[13] * g_LightProjectionMatrix[9]) - 
		(g_LightProjectionMatrix[14] * g_LightProjectionMatrix[10]);*/

	glActiveTextureARB(GL_TEXTURE7); CGLE();
	glMatrixMode(GL_TEXTURE); CGLE();
	glLoadIdentity(); CGLE();
	glLoadMatrixf(g_ShadowBias); CGLE();
	glMultMatrixf(g_LightProjectionMatrix); CGLE();
	glMultMatrixf(g_LightModelMatrix); CGLE();
	glMultMatrixf(g_InverseCamera); CGLE();
	glMatrixMode(GL_MODELVIEW);

	glViewport (
		0, 0, 
		g_ShadowWidth, g_ShadowHeight
	); CGLE();

	if (!check_shadow)
	{
		glEnable(GL_CULL_FACE); CGLE();
		glCullFace(GL_FRONT); CGLE();
		glDisable(GL_LIGHTING); CGLE();
		glShadeModel(GL_FLAT); CGLE();
		glDisable(GL_TEXTURE_2D); CGLE();
		glEnable(GL_POLYGON_OFFSET_FILL); CGLE();
		glColorMask(0, 0, 0, 0); CGLE();
	}

	// first pass
	s_Game->Render(check_shadow);

	glEnable(GL_TEXTURE_2D); CGLE();

	glBindTexture(GL_TEXTURE_2D, s_ShadowTexture); CGLE();
	glCopyTexSubImage2D (
		GL_TEXTURE_2D,		// target
		0,					// level
		0,					// x offset
		0,					// y offset	
		0,					// x
		0,					// y
		g_ShadowWidth,		// width
		g_ShadowHeight		// height
	); CGLE();

	if (!check_shadow)
	{
		glColorMask(1, 1, 1, 1); CGLE();
		glDisable(GL_POLYGON_OFFSET_FILL); CGLE();
		glShadeModel(GL_SMOOTH); CGLE();
		glEnable(GL_LIGHTING); CGLE();
		glCullFace(GL_BACK); CGLE();
		glDisable(GL_CULL_FACE); CGLE();
		glEnable(GL_DEPTH_TEST); CGLE();
	}

	glDisable(GL_TEXTURE_2D); CGLE();

	glMatrixMode(GL_TEXTURE); CGLE();
	glLoadIdentity(); CGLE();
	
	if (!check_shadow)
	{
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CGLE();
	}
}

void Engine::PreRender()
{
	// clear the screen
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	s_Game->PreRender();
}

void Engine::Render()
{
	if (check_shadow)
	{
		GenerateShadows();
		glutSwapBuffers();
	}
	else
	{
		GenerateShadows();
		
		glViewport (
			0, 0, 
			Window::GetWidth(), Window::GetHeight()
		); CGLE();

		glMatrixMode(GL_PROJECTION); CGLE();
		glLoadIdentity(); CGLE();
		gluPerspective (
			s_FOV, 
			(float)Window::GetWidth() / (float)Window::GetHeight(), 
			s_ZNear, s_ZFar
		); CGLE();
		glGetFloatv(GL_MODELVIEW_MATRIX, g_ProjectionMatrix); CGLE();

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity(); CGLE();
		Project();
		glGetFloatv(GL_MODELVIEW_MATRIX, g_ModelMatrix); CGLE();

		glActiveTextureARB(GL_TEXTURE6); CGLE();
		glMatrixMode(GL_TEXTURE); CGLE();
		glLoadIdentity(); CGLE();
		glLoadMatrixf(g_ModelMatrix); CGLE();
		glMultMatrixf(g_ProjectionMatrix); CGLE();
		//glRotatef(30.f, 0, 1, 0);
		glMatrixMode(GL_MODELVIEW);

		SwitchPerspective(Window::GetWidth(), Window::GetHeight());
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity(); CGLE();
		Project();

		PreRender();

			glEnable(GL_LIGHTING); CGLE();

			// lights
			for (std::vector<Light*>::iterator i = s_Lights.begin(); i != s_Lights.end(); ++i)
			{
				float pos[4] = { (*i)->GetPosition().x, (*i)->GetPosition().y, (*i)->GetPosition().z, 0 };

				int options = (*i)->GetOptions();

				glLightfv(GL_LIGHT0, GL_POSITION, pos); CGLE();
				if (options & LIGHT_AMBIENT)	{ glLightfv(GL_LIGHT0, GL_AMBIENT, (*i)->GetAmbient().GetOpenGLColor()); CGLE(); }
				if (options & LIGHT_DIFFUSE)	{ glLightfv(GL_LIGHT0, GL_DIFFUSE, (*i)->GetDiffuse().GetOpenGLColor()); CGLE(); }
				if (options & LIGHT_SPECULAR)	{ glLightfv(GL_LIGHT0, GL_SPECULAR, (*i)->GetSpecular().GetOpenGLColor()); CGLE(); } 
			}

			s_Game->Render();

		PostRender();
	}
}

void Engine::PostRender()
{
	s_Game->PostRender();

	// set up the camera
	glLoadIdentity(); CGLE();
	Project();

	// draw everything and swap the display buffer
	glutSwapBuffers(); CGLE();
}

void Engine::Project()
{
	s_Game->m_CurrentCam->Project();
}
So this code takes the matrix from the perspective of the light and multiplies it with the inverse of the eye camera. That way we get some nice values to use for the following shader: Lighting.vert
varying vec3 normal;
varying vec3 to_light;
varying vec3 eye;
varying vec3 pos;

varying vec4 shadow_coord;

attribute vec3 vTangent;

void main()
{
    // triangle
	
    normal = normalize(gl_NormalMatrix * gl_Normal);	
    vec3 tangent = normalize(gl_NormalMatrix * vec3(0, 1, 0));
    vec3 binormal = cross(normal, tangent);
	
    pos = vec3(gl_ModelViewMatrix * gl_Vertex);

    vec3 light_pos = vec3(gl_LightSource[0].position) - pos;
	
    to_light.x = dot(light_pos, tangent);
    to_light.y = dot(light_pos, binormal);
    to_light.z = dot(light_pos, normal);

    vec3 temp = -pos;
    eye.x = dot(temp, tangent);
    eye.y = dot(temp, binormal);
    eye.z = dot(temp, normal);
	
    mat4 matCam = gl_TextureMatrix[6];
    mat4 matModel = gl_TextureMatrix[5];
    mat4 matShadow = gl_TextureMatrix[7];

    // texturing
    gl_TexCoord[0] = gl_MultiTexCoord0;
	
    // camera
    gl_TexCoord[1] = gl_ModelViewMatrix * gl_Vertex;
    
    // shadow
    shadow_coord = matShadow * gl_ModelViewMatrix * gl_Vertex;	

    gl_Position = gl_ModelViewProjectionMatrix * matModel * gl_Vertex;
}
Lighting.frag
varying vec3 normal;
varying vec3 to_light;
varying vec3 eye;
varying vec3 pos;
varying vec4 shadow_coord;

uniform sampler2D tex_diffuse;
uniform sampler2D tex_specular;
uniform sampler2D tex_bump;
uniform sampler2D tex_alphakey;

uniform sampler2DShadow tex_shadows;

varying vec3 N, L, E, R;
varying float lambert;
varying vec2 uv;

varying vec4 final;

vec4 TexturingAlpha()
{
	vec4 result;

	vec4 texel_color = texture2D(tex_diffuse, uv);
	vec4 texel_alpha = texture2D(tex_alphakey, uv);

	result = texel_color * final;
	
	if (texel_alpha.a != 0.0)
	{
		float mask = (texel_alpha.r + texel_alpha.g + texel_alpha.b) / 3.0;
		result.a = mask;
	}
	
	return result;
}

void main()
{	
	uv = gl_TexCoord[0].st;
	
	N = normal;
	L = normalize(gl_LightSource[0].position.xyz);
	E = normalize(-pos);
	
	float dist = length(normalize(gl_LightSource[0].position.xyz - pos));
	float atten = 1.0 / (
		gl_LightSource[0].constantAttenuation + 
		gl_LightSource[0].linearAttenuation * dist +
		gl_LightSource[0].quadraticAttenuation * dist * dist
	);

	// ambient term
	vec4 ambient = (gl_LightSource[0].ambient * gl_FrontMaterial.ambient);
	
	// diffuse term
	vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0);
	
	// specular term
	vec4 specular = vec4(0.0, 0.0, 0.0, 1.0);
	
	final = ambient + (atten * gl_FrontMaterial.ambient);
	
	lambert = dot(N, L);
	if (lambert > 0.0)
	{
		final += gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * lambert * atten;
		
		float shiny = normalize(-reflect(L, N));
		float shiny2 = dot(shiny, E);
		if (shiny2 > 0.0)
		{
			float amount = pow(shiny2, gl_FrontMaterial.shininess);
			final += gl_LightSource[0].specular * gl_FrontMaterial.specular * amount * atten;
		}
	}
	
	vec4 shadow_color = vec4(0.0, 0.0, 0.0, 1.0);
	float shadowness = shadow2DProj(tex_shadows, shadow_coord).r;
	shadowness = clamp(shadowness, 0.0, 1.0);
	
	vec3 coord_pos = shadow_coord.xyz / shadow_coord.w;
	
	if (coord_pos.x >= 0.0 && coord_pos.y >= 0.0 && coord_pos.x <= 10.0 && coord_pos.y <= 10.0)
	{
		shadow_color.rgb = TexturingAlpha() * shadowness * final.rgb;
		gl_FragColor = shadow_color;
	}
	else
	{
		gl_FragColor = final;
	}
}
However, this code does not do what I want it to do. It does something like this: http://imgur.com/CHKHx.png (I apologize to future Googlers if the link is no longer available. Imagine a complex scene shaded in red, except for a square in the middle that is textured) Instead of checking if something is in the shade, it renders a nice light blob in front of everything. How can I fix my shadow mapping? Thanks in advance. [Edited by - knight666 on April 4, 2010 3:37:44 AM]

Share this post


Link to post
Share on other sites
Advertisement
Are you rendering the depth buffer to the shadowmap correctly? instead of glCopyTexSubImage2D maybe consider using Framebuffer objects like this.

in init()
// Generate shadow map Texture
glGenTextures(1, &shadowMap);
glBindTexture(GL_TEXTURE_2D, shadowMap);
glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, shadowMapSize, shadowMapSize, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri( GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
glBindTexture(GL_TEXTURE_2D, 0);

// Create FBO
glGenFramebuffersEXT(1,&frameBufferShadow);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferShadow);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D, shadowMap, 0);

// check FBO status
GLenum FBOstatus = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if(FBOstatus != GL_FRAMEBUFFER_COMPLETE_EXT)
printf("GL_FRAMEBUFFER_COMPLETE failed, CANNOT use FBO\n");

glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);




and this during render, with camera set to lights view

void Game::CreateShadowMap(){
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferShadow);

glClear(GL_DEPTH_BUFFER_BIT);

glPushAttrib( GL_VIEWPORT_BIT );
glViewport( 0, 0, shadowMapSize, shadowMapSize );
scene.DrawShadowMap(); //draws scene, unlit and untextured
glPopAttrib();

glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0);
}




I suggest rendering the shadow map to a textured quad to make sure it worked.

Share this post


Link to post
Share on other sites
I now render my depth to a framebuffer. I put it on the screen like this:

	if (check_shadow)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CGLE();

glDisable(GL_LIGHTING);

glViewport(0, 0, Window::GetWidth(), Window::GetHeight());

glMatrixMode(GL_TEXTURE);
glLoadIdentity();

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, s_ShadowTexture);
//glBindTexture(GL_TEXTURE_2D, g_TestTexture->GetID());

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
{
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
{
glLoadIdentity ();
glBegin(GL_QUADS);
{
glVertex3f(-1.0f, -1.0f, 0.0f); glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 0.0f); glTexCoord2f(0.0f, 1.0f);
glVertex3f(1.0f, 1.0f, 0.0f); glTexCoord2f(1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 0.0f); glTexCoord2f(1.0f, 0.0f);
}
glEnd();
}
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
glPopMatrix();

glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
}


I've verified with another texture that it works, but I get a beautiful white screen. :(

[Edited by - knight666 on April 4, 2010 3:19:57 AM]

Share this post


Link to post
Share on other sites
Try setting the GL_TEXTURE_COMPARE_MODE attribute of your depth texture to GL_NONE (might be by default, not sure. god, i _really_ have to check that some day). Also perhaps set the GL_DEPTH_TEXTURE_MODE attribute of your depth texture to GL_INTENSITY. Just to be sure :)
Note that depth 'colors' rendered using central projection may end up being very close to 1 - thus white - especially if you're using a larger depth range. What are the actual values of g_shadowNear and g_shadowFar?


Here's a version you could try:
Important note: you should call glTexCoord2f() _before_ calling glVertex3f(). glVertex...() finishes vertex definition and moves to the next vertex. Still you would most likely have ended up with a distorted but visible image. Plain white indicates some of the above things :)

	if (check_shadow)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); CGLE();

glDisable(GL_LIGHTING);

glViewport(0, 0, Window::GetWidth(), Window::GetHeight());

glMatrixMode(GL_TEXTURE);
glLoadIdentity();

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, s_ShadowTexture);

//insert texture attributes here or during texture construction, whichever you prefer:
glTexParameteri(GL_TEXTURE_2D,GL_DEPTH_TEXTURE_MODE,GL_INTENSITY);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_COMPARE_MODE,GL_NONE);

glMatrixMode(GL_MODELVIEW);
glPushMatrix();
{
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
{
glLoadIdentity ();
glBegin(GL_QUADS);
{
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 0.0f);
}
glEnd();
}
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
glPopMatrix();

glEnable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
}


Share this post


Link to post
Share on other sites
If I use those modes, I indeed get a depth texture. :D

Especially when I use these values:

float g_ShadowNear = 10.f;
float g_ShadowFar = 40000.f;



Instead of these:

float g_ShadowNear = 0.5f;
float g_ShadowFar = 25.f;



However, my shadows still don't get calculated properly. I still end up with a light blob somewhere.

[Edited by - knight666 on April 4, 2010 7:09:35 AM]

Share this post


Link to post
Share on other sites
I would advise against using shadow2DProj in your shader, instead do something like this.

Vertex

varying vec4 shadowTexCoord;

void main() {
shadowTexCoord = gl_TextureMatrix[7]*gl_ModelViewMatrix*gl_Vertex;
}








where the gl_TextureMatrix[7] is the ProjectionLight*ModelViewLight*ModelViewCameraInverse

The inverse might be hard to get, I used a class from the Game Programming Gems 1 CD.

Fragment

uniform sampler2D shadowMap;
varying vec4 shadowTexCoord;
void main() {
vec3 shadowPersp = shadowTexCoord.xyz/shadowTexCoord.w; // probably not neccisary for ortho.
float depth = texture2D(shadowMap,shadowPersp.xy).r;
float shadow=1.0;

if (depth+0.001<shadowPersp.z && shadowPersp.x>0.0 && shadowPersp.x<1.0 && shadowPersp.y>0.0 && shadowPersp.y<1.0)
shadow=0.0;








Setting up Light Matrix for shader.


glMatrixMode(GL_TEXTURE);
glMatrixMode(GL_TEXTURE);
glActiveTextureARB(GL_TEXTURE7);
glLoadIdentity(); // clear things up
glTranslated(0.5, 0.5, 0.5); // we have to clamp values in the [0.0, 1.0] range, not [-1.0, 1.0]
glScaled(0.5, 0.5, 0.5);
glMultMatrixf(lightProjMatrix); // now multiply by the matrices we have retrieved before
glMultMatrixf(lightMVMatrix);
float curMV[16];
glGetFloatv(GL_MODELVIEW_MATRIX, curMV);
matrix44 inverseMV;
inverseMV.col[0].x=curMV[0];inverseMV.col[0].y=curMV[1];inverseMV.col[0].z=curMV[2];inverseMV.col[0].w=curMV[3];
inverseMV.col[1].x=curMV[4];inverseMV.col[1].y=curMV[5];inverseMV.col[1].z=curMV[6];inverseMV.col[1].w=curMV[7];
inverseMV.col[2].x=curMV[8];inverseMV.col[2].y=curMV[9];inverseMV.col[2].z=curMV[10];inverseMV.col[2].w=curMV[11];
inverseMV.col[3].x=curMV[12];inverseMV.col[3].y=curMV[13];inverseMV.col[3].z=curMV[14];inverseMV.col[3].w=curMV[15];
inverseMV.invert();
curMV[0]=inverseMV.col[0].x;curMV[1]=inverseMV.col[0].y;curMV[2]=inverseMV.col[0].z;curMV[3]=inverseMV.col[0].w;
curMV[4]=inverseMV.col[1].x;curMV[5]=inverseMV.col[1].y;curMV[6]=inverseMV.col[1].z;curMV[7]=inverseMV.col[1].w;
curMV[8]=inverseMV.col[2].x;curMV[9]=inverseMV.col[2].y;curMV[10]=inverseMV.col[2].z;curMV[11]=inverseMV.col[2].w;
curMV[12]=inverseMV.col[3].x;curMV[13]=inverseMV.col[3].y;curMV[14]=inverseMV.col[3].z;curMV[15]=inverseMV.col[3].w;
glMultMatrixf(curMV);
glMatrixMode(GL_MODELVIEW);




[Edited by - Argo15 on April 4, 2010 10:46:21 AM]

Share this post


Link to post
Share on other sites
I've implemented it and this is my result: a tiny black square indicating my shadow, only it is dependent on the camera.

http://imgur.com/lIJ3T.png

Here is my codez for gl_TextureMatrix[7]:

glMatrixMode(GL_TEXTURE); CGLE();
glActiveTextureARB(GL_TEXTURE7); CGLE();
glLoadIdentity(); CGLE();
//glLoadMatrixf(g_ShadowBias); CGLE();

glScaled(0.5, 0.5, 0.5);
glTranslated(0.5, 0.5, 0.5);

glMultMatrixf(g_LightProjectionMatrix); CGLE();
glMultMatrixf(g_LightModelMatrix); CGLE();

float cam[16];

glGetFloatv(GL_MODELVIEW_MATRIX, cam);

g_InverseCamera[0] = cam[0];
g_InverseCamera[1] = cam[4];
g_InverseCamera[2] = cam[8];
g_InverseCamera[3] = 0.0f;

g_InverseCamera[4] = cam[1];
g_InverseCamera[5] = cam[5];
g_InverseCamera[6] = cam[9];
g_InverseCamera[7] = 0.0f;

g_InverseCamera[8] = cam[2];
g_InverseCamera[9] = cam[6];
g_InverseCamera[10] = cam[10];
g_InverseCamera[11] = 0.0f;

g_InverseCamera[12] =
-(cam[12] * cam[0]) -
(cam[13] * cam[1]) -
(cam[14] * cam[2]);

g_InverseCamera[13] =
-(cam[12] * cam[4]) -
(cam[13] * cam[5]) -
(cam[14] * cam[6]);

g_InverseCamera[14] =
-(cam[12] * cam[8]) -
(cam[13] * cam[9]) -
(cam[14] * cam[10]);

g_InverseCamera[15] = 1.0f;

glMultMatrixf(g_InverseCamera); CGLE();
//glMultMatrixf(cam); CGLE();

glMatrixMode(GL_MODELVIEW);



Here is my vertex shader:

	
varying vec3 normal;
varying vec3 to_light;
varying vec3 eye;
varying vec3 pos;

varying vec4 shadow_coord;

attribute vec3 vTangent;

void main()
{
// triangle

normal = normalize(gl_NormalMatrix * gl_Normal);
vec3 tangent = normalize(gl_NormalMatrix * vec3(0, 1, 0));
vec3 binormal = cross(normal, tangent);

pos = vec3(gl_ModelViewMatrix * gl_Vertex);

vec3 light_pos = vec3(gl_LightSource[0].position) - pos;

// to_light = -light_pos;
to_light.x = dot(light_pos, tangent);
to_light.y = dot(light_pos, binormal);
to_light.z = dot(light_pos, normal);

//eye = -pos;
vec3 temp = -pos;
eye.x = dot(temp, tangent);
eye.y = dot(temp, binormal);
eye.z = dot(temp, normal);

// texturing
gl_TexCoord[0] = gl_MultiTexCoord0;

mat4 matCam = gl_TextureMatrix[6];
mat4 matModel = gl_TextureMatrix[5];
mat4 matShadow = gl_TextureMatrix[7];

shadow_coord = matShadow * gl_ModelViewMatrix * gl_Vertex;

gl_Position = gl_ModelViewProjectionMatrix * matModel * gl_Vertex;
}


And the fragment shader:

varying vec3 normal;
varying vec3 to_light;
varying vec3 eye;
varying vec3 pos;
varying vec4 shadow_coord;

uniform sampler2D tex_diffuse;
uniform sampler2D tex_specular;
uniform sampler2D tex_bump;
uniform sampler2D tex_alphakey;

uniform sampler2D tex_shadows;
//uniform sampler2DShadow tex_shadows;

vec3 N, L, E, R;
float lambert;
vec2 uv;

varying vec4 final;

void main()
{
uv = gl_TexCoord[0].st;

N = normalize(normal);
L = normalize(gl_LightSource[0].position.xyz);
E = normalize(-pos);

float dist = length(normalize(gl_LightSource[0].position.xyz - pos));
float atten = 1.0 / (
gl_LightSource[0].constantAttenuation +
gl_LightSource[0].linearAttenuation * dist +
gl_LightSource[0].quadraticAttenuation * dist * dist
);

// ambient term
vec4 ambient = (gl_LightSource[0].ambient * gl_FrontMaterial.ambient);

// diffuse term
vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0);

// specular term
vec4 specular = vec4(0.0, 0.0, 0.0, 1.0);

final = ambient + (atten * gl_FrontMaterial.ambient);

lambert = dot(N, L);
if (lambert > 0.0)
{
final += gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * lambert * atten;

vec3 shiny = normalize(-reflect(L, N));
float shiny2 = dot(shiny, E);
if (shiny2 > 0.0)
{
float amount = pow(shiny2, gl_FrontMaterial.shininess);
final += gl_LightSource[0].specular * gl_FrontMaterial.specular * amount * atten;
}
}

vec4 shadow_color = vec4(0.0, 0.0, 0.0, 1.0);

vec3 shadow_perspective = shadow_coord.xyz / shadow_coord.w;

float depth = texture2D(tex_shadows, shadow_perspective.xy).r;
float shadow = 1.0;
float alpha = 1.0;

if (
depth + 0.001 < shadow_perspective.z &&
shadow_perspective.x > 0.0 &&
shadow_perspective.x < 1.0 &&
shadow_perspective.y > 0.0 &&
shadow_perspective.y < 1.0
)
{
shadow = 0.0;
alpha = 1.0;
}
else
{
shadow = 1.0;
}

shadow_color = TexturingAlpha() * shadow * final;

if (shadow == 1.0)
{
alpha = shadow_color.a;
}

gl_FragColor.rgb = shadow_color.rgb;
gl_FragColor.a = alpha;
}

Share this post


Link to post
Share on other sites
I'm not sure if you correctly found the inverse to the camera (idk I might be wrong I'm still fairly new to linear algebra =P), I'll post the inverse code i used.


class matrix44
{
public:
vector4 col[4];

matrix44() {};
~matrix44() {};

matrix44 &invert();
}






// Invert the matrix44
matrix44 &matrix44::invert()
{
matrix44 a(*this);
matrix44 b(IdentityMatrix44());

unsigned int r, c;
unsigned int cc;
unsigned int rowMax; // Points to max abs value row in this column
unsigned int row;
float tmp;

// Go through columns
for (c=0; c<4; c++)
{

// Find the row with max value in this column
rowMax = c;
for (r=c+1; r<4; r++)
{
if (fabs(a[c][r]) > fabs(a[c][rowMax]))
{
rowMax = r;
}
}

// Swap row "rowMax" with row "c"
for (cc=0; cc<4; cc++)
{
tmp = a[cc][c];
a[cc][c] = a[cc][rowMax];
a[cc][rowMax] = tmp;
tmp = b[cc][c];
b[cc][c] = b[cc][rowMax];
b[cc][rowMax] = tmp;
}

// Now everything we do is on row "c".
// Set the max cell to 1 by dividing the entire row by that value
tmp = a[c][c];
for (cc=0; cc<4; cc++)
{
a[cc][c] /= tmp;
b[cc][c] /= tmp;
}

// Now do the other rows, so that this column only has a 1 and 0's
for (row = 0; row < 4; row++)
{
if (row != c)
{
tmp = a[c][row];
for (cc=0; cc<4; cc++)
{
a[cc][row] -= a[cc][c] * tmp;
b[cc][row] -= b[cc][c] * tmp;
}
}
}

}

*this = b;

return *this;
}


Share this post


Link to post
Share on other sites
I ripped this from a friend:

void MatrixInverse(float* a_Output, float* a_OpenGLMatrix)
{
float tcell[16];

float tx = -a_OpenGLMatrix[12];
float ty = -a_OpenGLMatrix[13];
float tz = -a_OpenGLMatrix[14];

for (int h = 0; h < 3; h++)
{
for (int v = 0; v < 3; v++)
{
tcell[h + v * 4] = a_OpenGLMatrix[v + h * 4];
}
}

for (int i = 0; i < 11; i++)
{
a_Output = tcell;
}

a_Output[12] = tx * a_OpenGLMatrix[0] + ty * a_OpenGLMatrix[4] + tz * a_OpenGLMatrix[8];
a_Output[13] = tx * a_OpenGLMatrix[1] + ty * a_OpenGLMatrix[5] + tz * a_OpenGLMatrix[9];
a_Output[14] = tx * a_OpenGLMatrix[2] + ty * a_OpenGLMatrix[6] + tz * a_OpenGLMatrix[10];
}


When I multiply the new matrix with the old matrix I get the identity matrix, which is supposed to be a check to see if the function is working.

However, now I can't find my shadow square anymore. I'm going to try a bunch of scenes.

Share this post


Link to post
Share on other sites
If the camera is effecting the shadows it's either that the light matricies change when the camera changes, or the inverse matrix isn't un-doing the effects of the camera in the shader.

Is your shadowmap capturing the whole scene? Maybe put the shadowmap texture on a quad and post a picture.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement