Sign in to follow this  
csisy

OpenGL CSM (based on nvidia's paper) swimming

Recommended Posts

csisy    400
Hi there

I know, there are some similar topics, but I don't understand the solution. I made the CSM based on this paper: [url="http://developer.download.nvidia.com/SDK/10.5/opengl/src/cascaded_shadow_maps/doc/cascaded_shadow_maps.pdf"]http://developer.download.nvidia.com/SDK/10.5/opengl/src/cascaded_shadow_maps/doc/cascaded_shadow_maps.pdf[/url]
with some "improvements". Here is the code:

I have a matrix which is used when I create the shadows
[CODE]
float texOffset = 0.5f + (0.5f / (float)shadowSize);
float bias = 0.003f;
textureMat = Matrix(0.5f, 0.0f, 0.0f, 0.0f,
0.0f, -0.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
texOffset, texOffset, -bias, 1.0f);
[/CODE]
Now, here is the frustum corner's computing:
[CODE]
void Shadow::ComputeFrustumCorners()
{
float& camAspect = scene->camera->aspect;
Vector3& camEye = scene->camera->eyePosition;
Vector3 dir;
dir.x = scene->camera->GetView().m[0][2];
dir.y = scene->camera->GetView().m[1][2];
dir.z = scene->camera->GetView().m[2][2];
Vector3 x;
x.x = scene->camera->GetView().m[0][0];
x.y = scene->camera->GetView().m[1][0];
x.z = scene->camera->GetView().m[2][0];
Vector3 y;
y.x = scene->camera->GetView().m[0][1];
y.y = scene->camera->GetView().m[1][1];
y.z = scene->camera->GetView().m[2][1];
tanHalfFov = tanf(scene->camera->fov * 0.5f);
float nPlaneH = tanHalfFov * nearPlane;
float nPlaneW = nPlaneH * camAspect;
float fPlaneH = tanHalfFov * farPlane;
float fPlaneW = fPlaneH * camAspect;
Vector3 nPlaneX = x * nPlaneW;
Vector3 nPlaneY = y * nPlaneH;
Vector3 fPlaneX = x * fPlaneW;
Vector3 fPlaneY = y * fPlaneH;
nPlaneCenter = camEye + dir * nearPlane;
fPlaneCenter = camEye + dir * farPlane;
frustumCorners[0] = nPlaneCenter - nPlaneX - nPlaneY;
frustumCorners[1] = nPlaneCenter - nPlaneX + nPlaneY;
frustumCorners[2] = nPlaneCenter + nPlaneX + nPlaneY;
frustumCorners[3] = nPlaneCenter + nPlaneX - nPlaneY;
frustumCorners[4] = fPlaneCenter - fPlaneX - fPlaneY;
frustumCorners[5] = fPlaneCenter - fPlaneX + fPlaneY;
frustumCorners[6] = fPlaneCenter + fPlaneX + fPlaneY;
frustumCorners[7] = fPlaneCenter + fPlaneX - fPlaneY;
}
[/CODE]
I get the x,y,z axes from the view matrix, so I don't have to compute these values.

And of course the "main part" of CSM; compute the viewproj matrix for the shadow map generation, and the "final matrix" for the "final" shadow rendering. I think I should modify this part to kill the swimming edges.
[CODE]
void Shadow::ComputeMatrices()
{
ComputeFrustumCorners();
view = Matrix::LookAt(Vector3::Zero, light->direction, Vector3::Up);
Vector3 min = Vector3::Max;
Vector3 max = Vector3::Min;
Vector4 transformed;
for (int i = 0; i < NUM_CORNERS; i++)
{
transformed = Vector4::Transform(frustumCorners[i], view);
transformed /= transformed.w;
if (transformed.x < min.x)
min.x = transformed.x;
if (transformed.y < min.y)
min.y = transformed.y;
if (transformed.z < min.z)
min.z = transformed.z;
if (transformed.x > max.x)
max.x = transformed.x;
if (transformed.y > max.y)
max.y = transformed.y;
if (transformed.z > max.z)
max.z = transformed.z;
}
float scaleX = 2.0f / (max.x - min.x);
float scaleY = 2.0f / (max.y - min.y);
float offsetX = -0.5f * (min.x + max.x) * scaleX;
float offsetY = -0.5f * (min.y + max.y) * scaleY;
cropMat.m[0][0] = scaleX;
cropMat.m[1][1] = scaleY;
cropMat.m[2][2] = 1.0f;
cropMat.m[3][0] = offsetX;
cropMat.m[3][1] = offsetY;
cropMat.m[3][3] = 1.0f;
// INFO: bias
float bias = 10.0f;
min.z -= bias;
max.z += bias;
proj = Matrix::OrthographicOffCenter(-1, 1, -1, 1, min.z, max.z);
viewProj = view * proj * cropMat;
finalMat = viewProj * textureMat;
}
[/CODE]

So the problem is that, when I move or rotate the camera (not the light), the shadow edges are swimming / flickering. What is the solution for my code?

Thanks for all replies!

Share this post


Link to post
Share on other sites
MJP    19786
There's an article in ShaderX6 about stabilizing your cascades so that edges don't crawl as the camera moves, so if you have access to that you should give it a read. Otherwise I explained it in more detail in [url="http://www.gamedev.net/topic/591684-xna-40---shimmering-shadow-maps/"]this thread[/url].

The other option is to get your shadow filtering and resolution good enough so that you don't notice crawling edges, but doing this requires a combination of good shadow filtering techniques as well dynamic optimization of your cascade partitions based on what's visible to the camera.

Share this post


Link to post
Share on other sites
csisy    400
Thanks for the reply!

I put your code between the viewProj and the finalMat compute:

[CODE]
proj = Matrix::OrthographicOffCenter(-1, 1, -1, 1, min.z, max.z);
viewProj = view * proj * cropMat;
Vector3 shadowOrigin = Vector3::Transform(Vector3::Zero, viewProj);
shadowOrigin *= shadowHalfSize;
Vector2 roundedOrigin = Vector2(Helpers::MathHelper::Round(shadowOrigin.x), Helpers::MathHelper::Round(shadowOrigin.y));
Vector2 rounding = roundedOrigin - Vector2(shadowOrigin.x, shadowOrigin.y);
rounding /= ((float)shadowSize * 0.5f);
Matrix roundMatrix = Matrix::Translate(rounding.x, rounding.y, 0.0f);
viewProj *= roundMatrix;
finalMat = viewProj * textureMat;
[/CODE]

I think it works, because the static meshes' shadow is not flickering (I think [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]), but the character (the player) moves together with the camera, and its shadow is still flickering.

This can be solved by the bounding sphere instead of light AABB?

EDIT:
I read your post, and I understand that we need a fix size for the projection (this kills the flickering when rotating the camera) and a little round to texels (which kills the flickering when the camera moves). So I rewrite my code based on your code and the idea:
[CODE]
ComputeFrustumCorners();

// spheres for each split

Vector3 sphereCenter;
for (int i = 0; i < NUM_CORNERS; i++)
{
sphereCenter += frustumCorners[i];
}
sphereCenter /= NUM_CORNERS;

float sphereRadius = Vector3::Distance(sphereCenter, frustumCorners[0]);

float nearClip = 1.0f;
float backupDist = 10.0f + sphereRadius + nearClip;

Vector3 camPos = sphereCenter - light->direction * backupDist;
view = Matrix::LookAt(camPos, sphereCenter, Vector3::Up);

float bounds = sphereRadius * 2.0f;
float farClip = backupDist + sphereRadius;
proj = Matrix::Orthographic(bounds, bounds, nearClip, farClip);
viewProj = view * proj;

// round to texel

origin = Vector3::Transform(Vector3::Zero, viewProj);
origin *= shadowHalfSize;

originRounded.x = Helpers::MathHelper::Round(origin.x);
originRounded.y = Helpers::MathHelper::Round(origin.y);

rounding.x = originRounded.x - origin.x;
rounding.y = originRounded.y - origin.y;
rounding /= shadowHalfSize;

roundingMatrix = Matrix::Translate(rounding.x, rounding.y, 0.0f);
viewProj *= roundingMatrix;

// compute final components

finalMat = viewProj * textureMat;
viewFrustum->Update(viewProj);
[/CODE]

Is this code correct? If it is, there are some problem: my character (which moves with the camera) still flickering and the "backupDist" is really game and eyeposition relevant, so I can't hardcode it.

Or am I doing something wrong?

Share this post


Link to post
Share on other sites
MJP    19786
If geometry moves in world space then it is still going to flicker, you can't fix that by stabilizing cascades.

As for the backup distance, it's true that it's very annoying but you'd have the same problem in your original implementation, which is that objects behind the projection's near clip plane will get clipped out and so you have to have some means of "pulling back" the minz value. In D3D10/D3D11 there is actually a really nice solution to this problem, which is that you can turn of Z clipping and then objects behind the near clip plane won't get clipped. However as far as I know there is no equivalent for D3D9, so you're kind of stuck. The best you can do is try to automatically determine the required min z distance based on the extents of your level geometry.

Share this post


Link to post
Share on other sites
csisy    400
Thanks for your reply!

So isn't there any solution for the moving objects? And I have to compute dinamically the min and max values depended on the scene. I'll use a space-partitioning, maybe I will be able to use it to determine the min and max values.

Now, my static objects aren't flickering, and your solution is faster than my (nvidia's) old one, so it is awesome! :) Thanks for your help!

Share this post


Link to post
Share on other sites
csisy    400
Hm, it's strange. Yesterday, I didn't noticed this bug (see the pictures). I use this code now:

[CODE]
sphereCenter = Vector3::Zero;
for (int i = 0; i < NUM_CORNERS; i++)
{
sphereCenter += frustumCorners[i];
}
sphereCenter /= NUM_CORNERS;

sphereRadius = Vector3::Distance(sphereCenter, frustumCorners[0]);
sphereBounds = sphereRadius * 2.0f;

float nearClip = 1.0f;
float backupDist = 20.0f + nearClip + sphereRadius;
float farClip = backupDist + sphereRadius;

camPosition = sphereCenter - light->direction * backupDist;
view = Matrix::LookAt(camPosition, sphereCenter, Vector3::Up);

proj = Matrix::Orthographic(sphereBounds, sphereBounds, nearClip, farClip);
viewProj = view * proj;
[/CODE]

[attachment=9724:s1.JPG]
[attachment=9723:s2.JPG]

EDIT:
I compiled a Release from the code, here is the binaries, if someone would like to try it.
[attachment=9725:ShadowTest.zip]

Share this post


Link to post
Share on other sites
MJP    19786
It occurred to me that if you can't turn of z clipping, then you might be able to just clamp your vertex position to the near plane in the vertex shader by setting the projected z coordinate to max(z, 0.0f). I'm not sure if it would cause problems since I haven't tried it or heavily thought it through, but I think it might work. Then you could just size the orthographic projection to the min and max of the frustum.

Share this post


Link to post
Share on other sites
csisy    400
I render the shadowmap to the screen, and it looks like the sphereBounds was too "small". And I find the problem, I was stupid [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
When I computed the sphere's center, I get the radius from the d(center, corners[0]), which is the near-left-bottom corner of the frustum. The correct is the d(corners[0], corners[6]), where the 6th corner is the far-right-top corner.

[CODE]
sphereBounds = Vector3::Distance(frustumCorners[0], frustumCorners[6]);
sphereRadius = sphereBounds * 0.5f;
[/CODE]

Now, it works really good. Thanks for your help, the topic is solved (for me).

Ps.:
Can I set the topic to solved state, or set your post as a solution?

EDIT:
I have to use another little hardcoded thing:
[CODE]
sphereBounds = Vector3::Distance(frustumCorners[0], frustumCorners[6]) + 5.0f;
[/CODE]
because the camera sees the scene from top, and the sphereBounds wasn't big enough. Edited by csisy

Share this post


Link to post
Share on other sites
csisy    400
Hi again!

I've tested the shadows with a different camera view and I noticed that the shadowmap is maybe wrong. I uploaded a video yesterday which shows the problem:
[url="http://www.youtube.com/watch?v=HWmWCb2HdCA"]http://www.youtube.com/watch?v=HWmWCb2HdCA[/url]

When I turn the camera right the Sun should "looks" right too, but now the Sun "looks" left. And visa versa.

Here is the important code. Can anyone check it?

[CODE]
Shadow::Shadow(Base::Game* _game, Game::Scene* _scene)
: Renderer(_game, _scene)
{
vsShadowMap = 0;
vsShadowMapAnim = 0;
vsCombine = 0;

psShadowMap = 0;
psCombine = 0;

rtShadowMap = 0;
depthStencil = 0;
depthStencilOld = 0;

frustumCorners = 0;
viewFrustum = new ViewFrustum();

shadowSize = game->GetConfig()->GetShadowSize();
bias = 0.001f;

sphereBonus = 5.0f;
backupBonus = 20.0f;
}
[/CODE]
[CODE]
void Shadow::ComputeFrustumCorners()
{
float& camAspect = scene->camera->aspect;
Vector3& camEye = scene->camera->eyePosition;

Vector3 dir;
dir.x = scene->camera->GetView().m[0][2];
dir.y = scene->camera->GetView().m[1][2];
dir.z = scene->camera->GetView().m[2][2];

Vector3 x;
x.x = scene->camera->GetView().m[0][0];
x.y = scene->camera->GetView().m[1][0];
x.z = scene->camera->GetView().m[2][0];

Vector3 y;
y.x = scene->camera->GetView().m[0][1];
y.y = scene->camera->GetView().m[1][1];
y.z = scene->camera->GetView().m[2][1];

tanHalfFov = tanf(scene->camera->fov * 0.5f);

float nPlaneH = tanHalfFov * nearPlane;
float nPlaneW = nPlaneH * camAspect;
float fPlaneH = tanHalfFov * farPlane;
float fPlaneW = fPlaneH * camAspect;

Vector3 nPlaneX = x * nPlaneW;
Vector3 nPlaneY = y * nPlaneH;
Vector3 fPlaneX = x * fPlaneW;
Vector3 fPlaneY = y * fPlaneH;

nPlaneCenter = camEye + dir * nearPlane;
fPlaneCenter = camEye + dir * farPlane;

frustumCorners[0] = nPlaneCenter - nPlaneX - nPlaneY;
frustumCorners[1] = nPlaneCenter - nPlaneX + nPlaneY;
frustumCorners[2] = nPlaneCenter + nPlaneX + nPlaneY;
frustumCorners[3] = nPlaneCenter + nPlaneX - nPlaneY;

frustumCorners[4] = fPlaneCenter - fPlaneX - fPlaneY;
frustumCorners[5] = fPlaneCenter - fPlaneX + fPlaneY;
frustumCorners[6] = fPlaneCenter + fPlaneX + fPlaneY;
frustumCorners[7] = fPlaneCenter + fPlaneX - fPlaneY;
}
void Shadow::ComputeMatrices()
{
ComputeFrustumCorners();

// search corners' center
sphereCenter = Vector3::Zero;
for (int i = 0; i < NUM_CORNERS; i++)
{
sphereCenter += frustumCorners[i];
}
sphereCenter /= NUM_CORNERS;

// get sphere radius
sphereBounds = Vector3::Distance(frustumCorners[0], frustumCorners[6]) + sphereBonus;
sphereRadius = sphereBounds * 0.5f;

// near, far and cameraPosition
float nearClip = 1.0f;
float backupDist = nearClip + sphereRadius + backupBonus;
float farClip = backupDist + sphereRadius + sphereBonus;

camPosition = sphereCenter - light->direction * backupDist;
view = Matrix::CreateLookAt(camPosition, sphereCenter, Vector3::Up);

proj = Matrix::CreateOrthographic(sphereBounds, sphereBounds, nearClip, farClip);
viewProj = view * proj;

// round to texel

origin = Vector3::Transform(Vector3::Zero, viewProj);
origin *= shadowHalfSize;

originRounded.x = Helpers::MathHelper::Round(origin.x);
originRounded.y = Helpers::MathHelper::Round(origin.y);

rounding.x = originRounded.x - origin.x;
rounding.y = originRounded.y - origin.y;
rounding /= shadowHalfSize;

roundingMatrix = Matrix::CreateTranslate(rounding.x, rounding.y, 0.0f);
viewProj = viewProj * roundingMatrix;

// compute final components

finalMat = viewProj * textureMat;
viewFrustum->Update(viewProj);
}
[/CODE]

I would be grateful if anyone could help me. Edited by csisy

Share this post


Link to post
Share on other sites
Zoner    232
Stabilizing the shadowmap requires a few steps:
[list]
[*]Padding up the shadowmap by 1 additional texel than required, then translating the shadowmap projection by an offset so that the center texel is centered at all times. This will stop the crawling when you translate the camera.
[*]Mapping the visible part of the view frustum to a sphere before projected that into a texture, will protect it from crawls caused by rotating the camera.
[*]If your camera's field of view animates, the shadows will also crawl as the view frustum will dynamically make the fit sphere larger or smaller. This can be hidden by making taking the FOV and rounding it up into buckets of increments that affect the sphere fitting, or you can just live with it if you don't change the FOV more or at all. The bucket strategy will avoid the crawl but you will get pops when changing buckets instead. If you constrain the min and max FOV well enough you could probably use a single value and never see a pop.
[/list]

Share this post


Link to post
Share on other sites
csisy    400
I don't change the FOV. :) The only shadow flickering comes on when I move an object (the character with the camera). When I disabled the rounding the result was better for moving objects, but for static objects (of course) the flickering comes back. So for moving objects the rounding is the "bad step".

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  

  • Similar Content

    • By pseudomarvin
      I assumed that if a shader is computationally expensive then the execution is just slower. But running the following GLSL FS instead just crashes
      void main() { float x = 0; float y = 0; int sum = 0; for (float x = 0; x < 10; x += 0.00005) { for (float y = 0; y < 10; y += 0.00005) { sum++; } } fragColor = vec4(1, 1, 1 , 1.0); } with unhandled exception in nvoglv32.dll. Are there any hard limits on the number of steps/time that a shader can take before it is shut down? I was thinking about implementing some time intensive computation in shaders where it would take on the order of seconds to compute a frame, is that possible? Thanks.
    • By Arulbabu Donbosco
      There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window. 
      I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.
      anyone, please help me .. how to go further... to create an application like VR CAVE. 
       
      Thanks
    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
  • Popular Now