Sign in to follow this  

DX11 DX11 - Deferred Shadows - Not working

Recommended Posts

Hi guys wink.png .


So for a long time I've been doing shadows per object pixel, not deferred, and, I had to switch to the deferred way. Which I am now attempting, direct lighting works fine for e.g. Directional lights, but, for the shadows, it's another story. They simply don't work, the reason is unclear for now, so, I've come here in order to ask for your help smile.png


I'm almost (Hence the almost) certain that the cpus work isn't the fault here, but if the gpus work seems fine, I'll post the cpus work.


So, the code!


For generating the shadow map I'm almost certain that it's fine as the same shader was used for the previous method and nothing has changed, but, I'll post it: ( I do realize that loads of optimizations may be done here, like outputting the depth into a one channel render target )

cbuffer ConstantObjectBuffer : register (b0)
	matrix worldMatrix;
	matrix viewMatrix;
	matrix projectionMatrix;

	float state;
	float _instance;
	float _alphamap;

struct VOut
    float4 position : SV_POSITION;
    float2 texcoord : TEXCOORD;
    float4 depthPosition : TEXTURE0;

Texture2D t_alphamap : register(t0);
SamplerState ss;

VOut VShader(float4 position : POSITION, float2 texcoord : TEXCOORD, float3 instancePosition : INSTANCEPOS)
    VOut output;

    if (_instance == 1)
	position.x += instancePosition.x;
	position.y += instancePosition.y;
	position.z += instancePosition.z;

    position.w = 1.0f;
    output.texcoord = texcoord;

    output.position = mul(position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    // Store the position value in a second input value for depth value calculations.
    output.depthPosition = output.position;

    return output;

float4 PShader(VOut input) : SV_TARGET
    float4 color = float4(1,1,1,1);

    float depth = (input.depthPosition.z / input.depthPosition.w);
    color = float4(depth, depth, depth, 1);

    if (_alphamap == 1)
	color.a *= t_alphamap.Sample(ss, input.texcoord).a;

	return color;

PS. The resource filled by this shader looks fine, the shadow map I mean.


The directional deferred shader, rendered onto a full screen quad: (PS)

// Get Normal Data
float4 normal = t_normals.Sample(ss, input.Tex); // Stored in view space
	normal = mul(float4(, 0), texture_transform); // texture_transform == view^(-1)

// Get Position
float4 position = t_position.Sample(ss, input.Tex); // Stored in view space
	position = mul(float4(, 1), texture_transform);
normal.a = 1.0f;
position.w = 1.0f;

// Get Shadow Vertex Position
float4 lightViewPosition;
lightViewPosition = position;
lightViewPosition = mul(lightViewPosition, lightViewMatrix);
lightViewPosition = mul(lightViewPosition, lightProjectionMatrix);

float4 color = float4(0,0,0,1);

if (shadows == 1)
	color.rgb += GetShadowOcclusion(
		t_depthmap, // The shadow map
		1.0f // Specular Intensity
	float diffusebrightness = saturate(dot(normal, lDirection));
	color.rgb += lColor * diffusebrightness;

return color;


float4 GetShadowOcclusion(
	Texture2D ShadowMap, 
	float3 Normal, 
	float3 EyePos,
	float3 WorldPosition,
	float3 LightSurfaceDir, 
	float3 LightDirection,
	float3 LightColor, 
	float4 LightViewPosition, 
	float SpecularIntensity
	float bias;
	float4 color = float4(0,0,0,1);
		float2 projectTexCoord;
	float depthValue;
	float lightDepthValue;
	float lightIntensity;

	bias = 0.0001;
	float occlusion = 0;

	projectTexCoord.x =  LightViewPosition.x / LightViewPosition.w / 2.0f + 0.5f;
	projectTexCoord.y = -LightViewPosition.y / LightViewPosition.w / 2.0f + 0.5f;

	if((saturate(projectTexCoord.x) == projectTexCoord.x) && (saturate(projectTexCoord.y) == projectTexCoord.y))
		if (ShadowMap.Sample(ss, projectTexCoord).a == 0)
			color.a = 0.0f;

		depthValue = ShadowMap.Sample(ss, projectTexCoord).r;

		lightDepthValue = LightViewPosition.z / LightViewPosition.w;
		lightDepthValue = lightDepthValue - bias;

		lightIntensity = saturate(dot(Normal, LightSurfaceDir));

		if(lightDepthValue < depthValue)
			//float diffusebrightness = saturate(dot(normal, lDirection));
			//color.rgb += lColor * diffusebrightness;

			color.rgb += LightColor*lightIntensity;
			occlusion = lightIntensity;

        // Secular lighting occurs here, but it's irrelevant

I hope this will be enough to supply you with to approach this issue.


EDIT: I did not post any kind of result, so, where the shadows are not present are not being lit for some reason, it seems that the if(lightDepthValue < depthValue) is never fulfilled.


Thank you for your time. happy.png


Edited by Migi0027

Share this post

Link to post
Share on other sites
I'm not seeing anything obviously wrong. A couple suggestions though. Post a screenshot of the issue, run the DX debug device to make sure there are no DX errors or warnings, and change your shader to output these things to help debug: lightDepthValue, depthValue, depthValue - lightDepthValue. Also try rendering debug colors for shadow/non-shadow:

if(lightDepthValue < depthValue)
	return float4(1, 0, 0, 1);
return float4(0, 1, 0, 1);
Hopefully one of those will reveal where the issue lies.

Share this post

Link to post
Share on other sites

Not really related to the issue, but you can render your depth map directly to a depth stencil target (no need to use render target). This way you can take advantage of the fast z-buffer fills and you don't need to use a pixel shader at all (unless you'll need alpha transparency). 


In the shadowing code, most of the IFs are not necessary and won't add anything to the result. You can use clamping as shadow texture addressing mode.


I think also that your way of performing alpha testing is overly complicated.


the line "if (ShadowMap.Sample(ss, projectTexCoord).a == 0)color.a = 0.0f;" is unnecessary if you change the shadow pixel shader:

if (_alphamap == 1)
    if(t_alphamap.Sample(ss, input.texcoord).a == 0.0f)discard;



Share this post

Link to post
Share on other sites

Thanks for the input!


Yeah, it does seem that I've over complicated things, thanks for the points, I'll change them after I've fixed this issue smile.png .


Telanor: Actually I tried most of what you mentioned, and the behavior was: it passed the if((saturate(projectTexCoord.x) == projectTexCoord.x) && (saturate(projectTexCoord.y) == projectTexCoord.y)) but not the if(lightDepthValue < depthValue). I'm going to try the other points.



Share this post

Link to post
Share on other sites

Finally, it's working smile.png


In the older version I used to have a global view + projection matrix (for shadows), but as that changed, I needed to replace some variables with others, so I replaced almost all of the occurrences but forgot one, therefore it broke, and replacing the last one did the magic.


Thanks guys!

Edited by Migi0027

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  

  • Announcements

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By mister345
      Does buffer number matter in ID3D11DeviceContext::PSSetConstantBuffers()? I added 5 or six constant buffers to my framework, and later realized I had set the buffer number parameter to either 0 or 1 in all of them - but they still all worked! Curious why that is, and should they be set up to correspond to the number of constant buffers?
      Similarly, inside the buffer structs used to pass info into the hlsl shader, I added padding inside the c++ struct to make a struct containing a float3 be 16 bytes, but in the declaration of the same struct inside the hlsl shader file, it was missing the padding value - and it still worked! Do they need to be consistent or not? Thanks.
          struct CameraBufferType
              XMFLOAT3 cameraPosition;
              float padding;
    • By GreenGodDiary
      I'm attempting to implement some basic post-processing in my "engine" and the HLSL part of the Compute Shader and such I think I've understood, however I'm at a loss at how to actually get/use it's output for rendering to the screen.
      Assume I'm doing something to a UAV in my CS:
      RWTexture2D<float4> InputOutputMap : register(u0); I want that texture to essentially "be" the backbuffer.
      I'm pretty certain I'm doing something wrong when I create the views (what I think I'm doing is having the backbuffer be bound as render target aswell as UAV and then using it in my CS):
      DXGI_SWAP_CHAIN_DESC scd; ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC)); scd.BufferCount = 1; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT | DXGI_USAGE_UNORDERED_ACCESS; scd.OutputWindow = wndHandle; scd.SampleDesc.Count = 1; scd.Windowed = TRUE; HRESULT hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, NULL, NULL, NULL, D3D11_SDK_VERSION, &scd, &gSwapChain, &gDevice, NULL, &gDeviceContext); // get the address of the back buffer ID3D11Texture2D* pBackBuffer = nullptr; gSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); // use the back buffer address to create the render target gDevice->CreateRenderTargetView(pBackBuffer, NULL, &gBackbufferRTV); // set the render target as the back buffer CreateDepthStencilBuffer(); gDeviceContext->OMSetRenderTargets(1, &gBackbufferRTV, depthStencilView); //UAV for compute shader D3D11_UNORDERED_ACCESS_VIEW_DESC uavd; ZeroMemory(&uavd, sizeof(uavd)); uavd.Format = DXGI_FORMAT_R8G8B8A8_UNORM; uavd.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; uavd.Texture2D.MipSlice = 1; gDevice->CreateUnorderedAccessView(pBackBuffer, &uavd, &gUAV); pBackBuffer->Release();  
      After I render the scene, I dispatch like this:
      gDeviceContext->OMSetRenderTargets(0, NULL, NULL); m_vShaders["cs1"]->Bind(); gDeviceContext->CSSetUnorderedAccessViews(0, 1, &gUAV, 0); gDeviceContext->Dispatch(32, 24, 0); //hard coded ID3D11UnorderedAccessView* nullview = { nullptr }; gDeviceContext->CSSetUnorderedAccessViews(0, 1, &nullview, 0); gDeviceContext->OMSetRenderTargets(1, &gBackbufferRTV, depthStencilView); gSwapChain->Present(0, 0); Worth noting is the scene is rendered as usual, but I dont get any results from the CS (simple gaussian blur)
      I'm sure it's something fairly basic I'm doing wrong, perhaps my understanding of render targets / views / what have you is just completely wrong and my approach just makes no sense.

      If someone with more experience could point me in the right direction I would really appreciate it!

      On a side note, I'd really like to learn more about this kind of stuff. I can really see the potential of the CS aswell as rendering to textures and using them for whatever in the engine so I would love it if you know some good resources I can read about this!

      Thank you <3
      P.S I excluded the .hlsl since I cant imagine that being the issue, but if you think you need it to help me just ask

      P:P:S. As you can see this is my first post however I do have another account, but I can't log in with it because just keeps asking me to accept terms and then logs me out when I do over and over
    • By noodleBowl
      I was wondering if anyone could explain the depth buffer and the depth stencil state comparison function to me as I'm a little confused
      So I have set up a depth stencil state where the DepthFunc is set to D3D11_COMPARISON_LESS, but what am I actually comparing here? What is actually written to the buffer, the pixel that should show up in the front?
      I have these 2 quad faces, a Red Face and a Blue Face. The Blue Face is further away from the Viewer with a Z index value of -100.0f. Where the Red Face is close to the Viewer with a Z index value of 0.0f.
      When DepthFunc is set to D3D11_COMPARISON_LESS the Red Face shows up in front of the Blue Face like it should based on the Z index values. BUT if I change the DepthFunc to D3D11_COMPARISON_LESS_EQUAL the Blue Face shows in front of the Red Face. Which does not make sense to me, I would think that when the function is set to D3D11_COMPARISON_LESS_EQUAL the Red Face would still show up in front of the Blue Face as the Z index for the Red Face is still closer to the viewer
      Am I thinking of this comparison function all wrong?
      Vertex data just in case
      //Vertex date that make up the 2 faces Vertex verts[] = { //Red face Vertex(Vector4(0.0f, 0.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)), Vertex(Vector4(100.0f, 100.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)), Vertex(Vector4(100.0f, 0.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)), Vertex(Vector4(0.0f, 0.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)), Vertex(Vector4(0.0f, 100.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)), Vertex(Vector4(100.0f, 100.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)), //Blue face Vertex(Vector4(0.0f, 0.0f, -100.0f), Color(0.0f, 0.0f, 1.0f)), Vertex(Vector4(100.0f, 100.0f, -100.0f), Color(0.0f, 0.0f, 1.0f)), Vertex(Vector4(100.0f, 0.0f, -100.0f), Color(0.0f, 0.0f, 1.0f)), Vertex(Vector4(0.0f, 0.0f, -100.0f), Color(0.0f, 0.0f, 1.0f)), Vertex(Vector4(0.0f, 100.0f, -100.0f), Color(0.0f, 0.0f, 1.0f)), Vertex(Vector4(100.0f, 100.0f, -100.0f), Color(0.0f, 0.0f, 1.0f)), };  
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By turanszkij
      If I do a buffer update with MAP_NO_OVERWRITE or MAP_DISCARD, can I just write to the buffer after I called Unmap() on the buffer? It seems to work fine for me (Nvidia driver), but is it actually legal to do so? I have a graphics device wrapper and I don't want to expose Map/Unmap, but just have a function like void* AllocateFromRingBuffer(GPUBuffer* buffer, uint size, uint& offset); This function would just call Map on the buffer, then Unmap immediately and then return the address of the buffer. It usually does a MAP_NO_OVERWRITE, but sometimes it is a WRITE_DISCARD (when the buffer wraps around). Previously I have been using it so that the function expected the data upfront and would copy to the buffer between Map/Unmap, but now I want to extend functionality of it so that it would just return an address to write to.
  • Popular Now