• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
KaiserJohan

OpenGL
Directional light, shadow mapping and matrices..

14 posts in this topic

I'm using OpenGL and I've managed to get spotlight shadowmapping to work. I have the position and direction of the spotlight. The view matrix is constructed using glm::lookAt(), and the projection matrix is a perspective matrix.

For directional lights however, all I have is the light direction.

 

1) What is the view matrix and how to construct it, given only light direction?

2) What is the projection matrix and how is it constructed?

3) Do you still do a shadow map pass with directional lights before the actual lighting pass?

 

Thanks

0

Share this post


Link to post
Share on other sites

With a directional light, some things are simpler than a spotlight, like setting up the transforms.  A directional light uses a very simple orthographic projection, as opposed to a perspective projection.

 

However, most things are more complex because a directional light in theory affects everything out to infinity, but in practice your shadow texture is only a finite size and you don't want to stretch it over too large of an area or the resulting shadows will look very pixely.  Shadowmapping with a directional light is all about optimizing the shadow texture usage to make the projection of shadow map texels onscreen as small as possible.

 

In addition to the light direction, you'll need to define a frustum for your directional shadow camera.  An orthographic frustum is just a box oriented so that the z-axis is aligned with the projection direction.  The box should include everything that casts or receives a shadow, but at the same time you want the box to be as small as possible because your shadow texture will be stretched over the x and y extents of the box.  Minimizing the z-extents of the box isn't quite as critical, but still important, as this range is mapped into your shadow texture bit depth.

 

You'll want to calculate the position and size of this box based on your main camera's frustum.  If your main camera can see very far, like say 1000 meters, you won't be able to cover the whole area seen by your main camera with just one shadow texture.  A single shadow texture will only adequately cover a few tens of meters from the camera (depending on shadow texture resolution).  If you want to cover more area then that, you may want to look into cascaded shadow mapping and similar techniques.

 

Once your shadow camera frustum is defined, the matrices are quite simple to set up.

1. The view matrix is just a transform with only position and rotation, centered in the center of the box and rotated  to align with the box.

2. The projection matrix is just a pure scale matrix that maps the extents of the box into clip space (so each axis is mapped into a -1 to 1 range).

3. Yes you still need to render the shadow texture.  With cascaded shadow mapping, you'll need to render MULTIPLE shadow textures.

2

Share this post


Link to post
Share on other sites

The view matrix - why is it in the center of the box, and not infront of it? Otherwise wont half of the geometry be outside the view? And aligned, as in looking down the -Z axis?

Projection matrix - how would you calculate such a scale matrix? Does glm::ortho, which creates an orthographic matrix, do the same thing?

Edited by KaiserJohan
0

Share this post


Link to post
Share on other sites

The view matrix, I chose to put the origin of the view transform in the center of the box because it simplifies constructing the projection matrix.  You can put the view transform at one end of the box or the other if you prefer, but then you'll need to introduce a translation component into the projection matrix to compensate.  It's just easier to put it at the center.

 

And yes, the -Z axis.

 

The projection matrix would just be:

 

   1/he.x      0          0         0

    0         1/he.y      0         0

    0          0          1/he.z    0

    0          0          0         1

 

(where "he" is the half-extents of your box).

 

Also you could use glOrtho( -he.x, he.x, -he.y, he.y, -he.z, he.z ) to define the projection matrix if you like.  (I may have flipped the signs on z there)

It is probably safer to use glOrtho, as I'm not completely sure about the range of clipping coordinates in z.

Edited by lunkhound
1

Share this post


Link to post
Share on other sites

I've got shadow mapping working, using the following matrices:

Mat4 viewMatrix = LookAt(cameraPosition + (directionalLight.mLightDirection * Z_FAR/2.0f), -directionalLight.mLightDirection, Vec3(0.0f, 1.0f, 0.0f));
Mat4 lightVP = CreateOrthographicMatrix(-Z_FAR, Z_FAR, -Z_FAR, Z_FAR, Z_NEAR, Z_FAR) * viewMatrix;

The problem is when moving around the camera, so does the shadows move around, which is unrealistic. What is the proper way to build the view matrix?

Edited by KaiserJohan
0

Share this post


Link to post
Share on other sites

What you have there doesn't look right at all.  It isn't that easy.

I would do it something like this:

 

  1. Find a vector orthogonal to the light direction.

  2. Use the cross-product to find another vector orthogonal to the other two.  Now you have 3 orthogonal unit vectors.

  3. Form a rotation matrix from the 3 vectors.  The light direction should be the z-axis, and the other two are x and y.  Make sure the handedness is correct.  The x-axis cross y-axis should equal the z-axis, not the negative z-axis.  This rotation matrix transforms directions from world space into the light space.

  4. Generate a list of the 8 corner vertices of the main camera's frustum.  You'll need the main camera's position, z-near, z-far, horizontal field of view, and vertical field of view.

  5. Loop over the 8 corner vertices, and apply the rotation matrix to each in turn and record the minimum and maximum on the x, y, and z axes.  This gives the extents of the box I mentioned in an earlier post.

  6. Find the coordinates of the center of the box in light space i.e. ((xmin + xmax)*0.5, (ymin + ymax)*0.5, (zmin + zmax)*0.5)

 

Now it is straightforward to assemble the shadowmap view matrix.  The 3x3 rotation matrix goes into the rotation part of the 4x4 matrix.  For the translation part of the matrix, you want to the box-center coordinates NEGATED.  And the last row of the matrix is just (0 0 0 1).

1

Share this post


Link to post
Share on other sites

Thanks for the reply. I've tried it, but I do not seem to get any shadows. Here is an image:

 

shadow1.png

 

I tried it with the following code, as per your suggestions:

        for (const RenderableLighting::DirectionalLight& directionalLight : lighting.mDirectionalLights)
        {
            Vec3 lightDir = directionalLight.mLightDirection;   // = Vec3(0.0f, 1.0f, 1.0f)
            Vec3 perpVec1(1.0f, 0.0f, 0.0f);
            Vec3 perpVec2(0.0f, 1.0f, -1.0f);
            Mat3 rotationMatrix;                // using glm, so matrices are column-major
            rotationMatrix[0] = perpVec1;
            rotationMatrix[1] = perpVec2;
            rotationMatrix[2] = lightDir;

            assert(glm::cross(perpVec1, perpVec2) == lightDir);

            Vec3 corners[8] = {Vec3(-25.0f, -25.0f, 25.0f), Vec3(-25.0f, -25.0f, -25.0f), Vec3(-25.0f, 25.0f, 25.0f), Vec3(-25.0f, 25.0f, -25.0f),
                               Vec3(25.0f, -25.0f, 25.0f), Vec3(25.0f, -25.0f, -25.0f), Vec3(25.0f, 25.0f, 25.0f), Vec3(25.0f, 25.0f, -25.0f) };

            for (uint32_t i = 0; i < 8; i++)
                corners[i] = corners[i] * rotationMatrix;

            float minX = corners[0].x, minY = corners[0].y, minZ = corners[0].z, maxX = corners[0].x, maxY = corners[0].y, maxZ = corners[0].z;
            for (uint32_t i = 0; i < 8; i++)
            {
                if (corners[i].x < minX)
                    minX = corners[i].x;
                if (corners[i].x > maxX)
                    maxX = corners[i].x;
                if (corners[i].y < minY)
                    minY = corners[i].y;
                if (corners[i].y > maxY)
                    maxY = corners[i].y;
                if (corners[i].z < minZ)
                    minZ = corners[i].z;
                if (corners[i].z > maxZ)
                    maxZ = corners[i].z;
            }

            Mat4 viewMatrix(rotationMatrix);
            viewMatrix[3][0] = -(minX + maxX) * 0.5f;
            viewMatrix[3][1] = -(minY + maxY) * 0.5f;
            viewMatrix[3][2] = -(minZ + maxZ) * 0.5f;
            viewMatrix[0][3] = 0.0f;
            viewMatrix[1][3] = 0.0f;
            viewMatrix[2][3] = 0.0f;
            viewMatrix[3][3] = 1.0f;

            Mat4 lightVP = glm::ortho(minX, minX, minY, maxY, minZ, maxZ) * viewMatrix;

            GLCALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mDirectionalShadowMap.mFramebuffer));
            GLCALL(glDrawBuffer(GL_NONE));
            DirLightShadowPass(directionalLight, lightVP, renderQueue);

            GLCALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mGBuffer.mFramebuffer));
            GLCALL(glDrawBuffer(GBuffer::GBUFFER_COLOR_ATTACHMENT_FINAL));
            DirLightLightingPass(directionalLight, gNDCBiasMatrix * lightVP, lighting.mGamma, lighting.mScreenSize);
        }

Do you spot anything that stands out? Besides the view/projection calculations, the rest should be fine

Edited by KaiserJohan
0

Share this post


Link to post
Share on other sites

Well, the rotation matrix has some problems for starters.  The rows of the rotation matrix all need to be unit magnitude (some of yours aren't), and they need to be perpendicular to each other (also not true for your matrix).  So what you've got there is a matrix that scales, skews, and rotates.

 

Another problem that jumps out is that you aren't calculating the corners of the main camera's frustum.  Instead you've got the corners of a 50 x 50 x 50 box centered on the origin.  Your main camera has a perspective projection matrix, so the shape of it isn't a box, it is more of a truncated pyramid.

If you take your main camera's view-projection matrix, invert it (note, NOT a simple transpose), and then run the corners of a 2 x 2 x 2 box centered on the origin through it, that should give the corners of your camera's frustum.

 

Also your orthographic matrix is also wrong.  You should calculate the half-extents of the box from your minX, maxX, etc, and express the ortho in terms of the half-extents.

1

Share this post


Link to post
Share on other sites

I'm using the cross product to find out the perpendicular vectors; I forgot to normalize lightDirection - the following should give me the proper rotation matrix no?

            Vec3 lightDir = glm::normalize(directionalLight.mLightDirection);   // = Vec3(0.0f, 1.0f, 1.0f)
            Vec3 perpVec1 = glm::cross(lightDir, Vec3(0.0f, 0.0f, 1.0f));
            Vec3 perpVec2 = glm::normalize(glm::cross(lightDir, perpVec1));
            Mat3 rotationMatrix;                // using glm, so matrices are column-major
            rotationMatrix[0] = perpVec1;
            rotationMatrix[1] = perpVec2;
            rotationMatrix[2] = lightDir;

            assert(glm::dot(lightDir, perpVec1) == 0);
            assert(glm::dot(lightDir, perpVec2) == 0);

As for the corners of the camera frustrum, I'm thinking one step at a time, the simplest would be to just use static boundaries like the box I posted, it would work just as well for the moment, right?

 

When you say half-extents, you mean the min/max divided by two, like this?

Mat4 lightVP = glm::ortho(minX/2.0f, minX/2.0f, minY/2.0f, maxY/2.0f, minZ/2.0f, maxZ/2.0f) * viewMatrix;
0

Share this post


Link to post
Share on other sites

You also need to normalize the first cross product there (perpVec1).

 

If the 50x50x50 box encloses your scene, then yes that should work fine as a temporary hack.

 

The extents would be:

 

Vec3 extents( maxX - minX, maxY - minY, maxZ - minZ );

 

The half extents would just be 0.5 * extents:

 

Vec3 he = extents * 0.5;

 

Then you want something like ortho( -he.x, he.x, -he.y, he.y, -he.z, he.z );

 

Otherwise, you'll have unwanted translation in the projection matrix.  Translation that already exists in the view matrix so you'd be applying it twice.

1

Share this post


Link to post
Share on other sites

Thanks, I've got shadows working with the static bounding box, I'll be trying what you wrote in an earlier post about inverting the camera view/projection matrix. One thing though, what do you mean by

 

 

 

run the corners of a 2 x 2 x 2 box centered on the origin through it

 

?

0

Share this post


Link to post
Share on other sites

The corners of a 2x2x2 box at the origin are 8 vertices where each component is either a 1 or a -1.  Vec3(1,1,1), Vec3(-1,1,1), .. and so on.  This corresponds to the view volume in clip-space.  The view-projection matrix maps from world space to clip space (it is the concatenation of the view matrix and the projection matrix).  So if you invert the view-projection matrix, it will map from clip space to world space.  If you apply the inverse-view-projection matrix to each of the 8 corners, you should end up with the 8 corners of the view volume in world-space.  The inverse-view-projection matrix will be a 4x4 matrix, so each of your vertices will need to be "promoted" to a Vec4 with a w-component of 1, and the result will be in homogeneous coordinates so you will need to divide by w after the transform.

1

Share this post


Link to post
Share on other sites

If I understod correctly;

        Mat4 rotationMatrix(Vec4(perpVec1, 0.0f), Vec4(perpVec2, 0.0f), Vec4(lightDir, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f));  // again, column major

        Vec4 corners[8] = { Vec4(-1.0f, -1.0f, 1.0f, 1.0f), Vec4(-1.0f, -1.0f, -1.0f, 1.0f), Vec4(-1.0f, 1.0f, 1.0f, 1.0f), Vec4(-1.0f, 1.0f, -1.0f, 1.0f),
                            Vec4(1.0f, -1.0f, 1.0f, 1.0f), Vec4(1.0f, -1.0f, -1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, -1.0f, 1.0f) };
        const Mat4 inverseVPMatrix = glm::inverse(viewProjectionMatrix);    // the cameras view-projection matrix
        for (uint32_t i = 0; i < 8; i++)
        {
            corners[i] = corners[i] * inverseVPMatrix;
            corners[i] /= corners[i].w;
        }

        for (uint32_t i = 0; i < 8; i++)
            corners[i] = corners[i] * rotationMatrix;

Looking at the corners after multiplying with the inverse VPMatrix and dividing by w, the values all seem to be in the range of [-2.0, 2.0]. which can't be right?

Edited by KaiserJohan
0

Share this post


Link to post
Share on other sites

That doesn't sound right.  I don't see anything wrong with the code there.  There must be something wrong with the viewProjection matrix, make sure view and projection are concatenated in the correct order.  For column major matrices, it should be projection * view, not the other way around.

1

Share this post


Link to post
Share on other sites

Turned out the issue was with wrong order of multiplication of the corners and inverse VP matrix. This is the correct one:

corners[i] = inverseVPMatrix * corners[i];

Perhaps due to glm being column major?

 

I consider this topic solved; big thanks for all the help! I'm gonna investigate cascaded shadow mapping next, 

0

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  
Followers 0

  • Similar Content

    • By Toastmastern
      So it's been a while since I took a break from my whole creating a planet in DX11. Last time around I got stuck on fixing a nice LOD.
      A week back or so I got help to find this:
      https://github.com/sp4cerat/Planet-LOD
      In general this is what I'm trying to recreate in DX11, he that made that planet LOD uses OpenGL but that is a minor issue and something I can solve. But I have a question regarding the code
      He gets the position using this row
      vec4d pos = b.var.vec4d["position"]; Which is then used further down when he sends the variable "center" into the drawing function:
      if (pos.len() < 1) pos.norm(); world::draw(vec3d(pos.x, pos.y, pos.z));  
      Inside the draw function this happens:
      draw_recursive(p3[0], p3[1], p3[2], center); Basically the 3 vertices of the triangle and the center of details that he sent as a parameter earlier: vec3d(pos.x, pos.y, pos.z)
      Now onto my real question, he does vec3d edge_center[3] = { (p1 + p2) / 2, (p2 + p3) / 2, (p3 + p1) / 2 }; to get the edge center of each edge, nothing weird there.
      But this is used later on with:
      vec3d d = center + edge_center[i]; edge_test[i] = d.len() > ratio_size; edge_test is then used to evaluate if there should be a triangle drawn or if it should be split up into 3 new triangles instead. Why is it working for him? shouldn't it be like center - edge_center or something like that? Why adding them togheter? I asume here that the center is the center of details for the LOD. the position of the camera if stood on the ground of the planet and not up int he air like it is now.

      Full code can be seen here:
      https://github.com/sp4cerat/Planet-LOD/blob/master/src.simple/Main.cpp
      If anyone would like to take a look and try to help me understand this code I would love this person. I'm running out of ideas on how to solve this in my own head, most likely twisted it one time to many up in my head
      Thanks in advance
      Toastmastern
       
       
    • By fllwr0491
      I googled around but are unable to find source code or details of implementation.
      What keywords should I search for this topic?
      Things I would like to know:
      A. How to ensure that partially covered pixels are rasterized?
         Apparently by expanding each triangle by 1 pixel or so, rasterization problem is almost solved.
         But it will result in an unindexable triangle list without tons of overlaps. Will it incur a large performance penalty?
      B. A-buffer like bitmask needs a read-modiry-write operation.
         How to ensure proper synchronizations in GLSL?
         GLSL seems to only allow int32 atomics on image.
      C. Is there some simple ways to estimate coverage on-the-fly?
         In case I am to draw 2D shapes onto an exisitng target:
         1. A multi-pass whatever-buffer seems overkill.
         2. Multisampling could cost a lot memory though all I need is better coverage.
            Besides, I have to blit twice, if draw target is not multisampled.
       
    • By mapra99
      Hello

      I am working on a recent project and I have been learning how to code in C# using OpenGL libraries for some graphics. I have achieved some quite interesting things using TAO Framework writing in Console Applications, creating a GLUT Window. But my problem now is that I need to incorporate the Graphics in a Windows Form so I can relate the objects that I render with some .NET Controls.

      To deal with this problem, I have seen in some forums that it's better to use OpenTK instead of TAO Framework, so I can use the glControl that OpenTK libraries offer. However, I haven't found complete articles, tutorials or source codes that help using the glControl or that may insert me into de OpenTK functions. Would somebody please share in this forum some links or files where I can find good documentation about this topic? Or may I use another library different of OpenTK?

      Thanks!
    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
  • Popular Now