• Advertisement
Sign in to follow this  

OpenGL GLSL shadows not working

This topic is 1987 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

I copied this code from the tutorial at gametutorials.com and this is what I see in my game:


Here is the code:


void RenderWorld()

inline void RenderPlayScene()
// Set the current viewport to our texture size
glViewport(0, 0, (int)SHADOW_WIDTH, (int)SHADOW_HEIGHT);
// Now we just need to set the matrices for the light before we render

// Push on a matrix to make sure we can restore to the old matrix easily
// Set the current projection matrix to our light's projection matrix
// Load modelview mode to set our light's modelview matrix
// Load the light's modelview matrix before we render to a texture
// Since we don't care about color when rendering the depth values to
// the shadow-map texture, we disable color writing to increase speed.
// Eliminate artifacts caused by shadow mapping
glPolygonOffset(8.0f, 4.0f);

// This turns of the polygon offset functionality to fix artifacts.
// Comment this out and run the program to see what artifacts I mean.
// Render the world according to the light's view
// Now that the world is rendered, save the depth values to a texture
glBindTexture(GL_TEXTURE_2D, g_renderTexture);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, (int)SHADOW_WIDTH, (int)SHADOW_HEIGHT);
// We can turn color writing back on since we already stored the depth values
// Turn off polygon offsetting
// Restore our normal viewport size to our screen width and height
glViewport(0, 0, (int)g_width, (int)g_height);
// Go back to the projection mode and restore the original matrix
// Restore the original projection matrix
// Go back to modelview model to start drawing like normal
// Clear the color and depth bits and start over from the camera's view
// After we have switched backed to our camera's view, we need to
// grab the inverse of the modelview's matrix. If you are unfamiliar
// with what an inverse of a matrix does, let's review. If you
// multiply a matrix by it's inverse, it basically zeros it out.
// We need the inverse because in the vertex shader we will have a
// vertex that is multiplied by the camera's view matrix (modelview),
// and we need to bring that back down to world space and project
// it into the light's clip space. Since we are working in the light's
// clip space and not the camera's clip space this needs to happen.
// For this to work, we need to make sure we have called the Look()
// function from the camera object before calling GetInverseMatrix().
// Pass in the global matrix that will store our modelview inverse matrix.
// This function grabs the current modelview matrix and returns the inverse.
// Render the world and apply the shadow map texture to it
glLightfv( GL_LIGHT0, GL_POSITION, g_LightPosition );

void RenderScene()
if(g_mode == PLAY)
if(g_mode == PLAY)


void StoreLightMatrices()
// Reset our current light matrices
memset(g_mModelView, 0, sizeof(float)*16);
memset(g_mProjection, 0, sizeof(float)*16);
// Let's push on a new matrix so we don't change the rest of the world
// Push on a new matrix to keep our view changes isolated
// Reset the current modelview matrix
// This is where we set the light's position and view.
gluLookAt(g_LightPosition[0], g_LightPosition[1], g_LightPosition[2],
g_LightView[0], g_LightView[1], g_LightView[2], 0, 1, 0);
// Now that we have the light's view, let's save the current modelview matrix.
glGetFloatv(GL_MODELVIEW_MATRIX, g_mModelView);
// Now pop off the current light view's matrix
// Reset the current matrix
// Set our FOV, aspect ratio, then near and far planes for the light's view
gluPerspective(60.0f, 1.0f, 0.5f, 25.0f);
// Grab the current matrix that will be used for the light's projection matrix
glGetFloatv(GL_MODELVIEW_MATRIX, g_mProjection);
// Go back to the original matrix
void CreateRenderTexture(int sizeX, int sizeY, int channels, int type)
// Create a pointer to store the blank image data
unsigned int *pTexture = NULL;
// Store the current channels to be allocated by default
int channelsTrue = channels;
// If the channels are greater than 4 there must be a special flag like
// GL_DEPTH_COMPONENT, so make sure we only allocate 1 bit per pixel.
if(channels > 4)
channelsTrue = 1;
// Allocate and init memory for the image array and point to it from pTexture
pTexture = new unsigned int [sizeX * sizeY * channelsTrue];
memset(pTexture, 0, sizeX * sizeY * channelsTrue * sizeof(unsigned int));
// Register the texture with OpenGL and bind it to the texture ID
glGenTextures(1, &g_renderTexture);
glBindTexture(GL_TEXTURE_2D, g_renderTexture);

// Create the texture and store it on the video card
glTexImage2D(GL_TEXTURE_2D, 0, channels, sizeX, sizeY, 0, type, GL_UNSIGNED_INT, pTexture);

// Set the texture quality
// Since we stored the texture space with OpenGL, we can delete the image data
delete [] pTexture;
void RenderWorld();
void ApplyShadowMap()

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

// This function is the main function that needs to be changed from the
// previous tutorial. We needed to take out the texture generation code
// so a couple things will change. This means we will need to turn our
// shadow on, as well as multiply the inverse of our camera matrix by
// the light's projection and modelview matrix. We still include the
// bias matrix to convert the clip space to a 0 to 1 ratio instead of
// a -1 to 1 ratio.
// Let's turn our shaders on for doing shadow mapping on our world
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

// Turn on our texture unit for shadow mapping and bind our depth texture
glBindTexture(GL_TEXTURE_2D, g_renderTexture);

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// In order for the shader to have access to our light's texture of depth
// values, we need to tell our fragment shader the texture unit that our
// texture is being bound to. Since we use GL_TEXTURE0_ARB we pass in 0.
GLuint uniform = glGetUniformLocationARB(g_Shader.GetProgram(), "shadowMap");
glUniform1iARB(uniform, 0);
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

// Here is where we set the mode and function for shadow mapping with shadow2DProj().
// Create our bias matrix to have a 0 to 1 ratio after clip space
const float mBias[] = {0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0};
glLoadMatrixf(mBias); // The bias matrix to convert to a 0 to 1 ratio
glMultMatrixf(g_mProjection); // The light's projection matrix
glMultMatrixf(g_mModelView); // The light's modelview matrix

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// Instead of using texture generation functions that handle the inverse
// camera matrix for us, we calculated this ourselves and need to multiply
// it by the preceding matrices. Remember the equation for projection:
// mProjectedTexture = mLightProjection * mLightModelview * mCameraInverse;
// We need to use this because we are projecting the shadow map onto the
// world from the light's position. A bit tricky to wrap your head around?
// Keep in mind, the camera's inverse matrix is really the modelview matrix
// inverted with the camera already applied to it.
// Following the above equation, multiply our camera's inverse by the matrices.
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *

glMatrixMode(GL_MODELVIEW); // Switch back to normal modelview mode
RenderWorld(); // Render the world that needs to be shadowed
// Now that the world is shadowed and we are done with the texture generation,
// let's set everything back to normal by resetting the texture matrix.
// Turn the first multi-texture pass off

/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *
// Light expected, we need to turn our shader off since we are done
/////// * /////////// * /////////// * NEW * /////// * /////////// * /////////// *


uniform sampler2DShadow shadowMap;
varying vec4 projCoord;
void main ()
const float kTransparency = 0.3;
vec4 color = gl_Color;
float rValue = shadow2DProj(shadowMap, projCoord).r + kTransparency;
rValue = clamp(rValue, 0.0, 1.0);
vec3 coordPos = projCoord.xyz / projCoord.w;
if(coordPos.x >= 0.0 && coordPos.y >= 0.0 && coordPos.x <= 1.0 && coordPos.y <= 1.0 )
gl_FragColor = color * rValue;
gl_FragColor = color;


varying vec4 projCoord;
void main()
vec4 realPos = gl_ModelViewMatrix * gl_Vertex;

projCoord = gl_TextureMatrix[0] * realPos;
gl_FrontColor = gl_Color;
gl_Position = ftransform();

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?
    • 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