Quantcast
Channel: Question and Answer » hlsl
Viewing all articles
Browse latest Browse all 69

How do I sample a Depth/Stencil Texture in HLSL?

$
0
0

I am shadow mapping in Direct3D 9. I’m trying to avoid rendering depth to a 32-bit render target. So, I’ve created a depth/stencil texture( a texture w/usage Depth/Stencil ). When I render I do this:

//device
IDirect3DDevice9 *pd3dDevice = GetDevice();

// set an rt the same size as the depth/stencil texture(needs attention...this render target will not be rendered to)
pd3dDevice->SetRenderTarget(0, GetShadowMapRT());

// set the shadow map depth/stencil texture surface
pd3dDevice->SetDepthStencilSurface(GetShadowMapDSSurface());

pd3dDevice.SetStreamSource(0, GDEOctree.Geometry,
                Constants.OctreeVertexSize * GDEOctree.StaticGeometryVertexCount, 12);

// set vertex format
pd3dDevice.VertexFormat = SlimDX.Direct3D9.VertexFormat.Position;

// set indices
pd3dDevice.Indices = GDEOctree.ShadowCasterIndices;

// set render states
DeviceManager.SetRenderState(RenderState.ZEnable, 1);
DeviceManager.SetRenderState(RenderState.ZWriteEnable, 1);
DeviceManager.SetRenderState(RenderState.ZFunc, (int)Compare.LessEqual);
DeviceManager.SetRenderState(RenderState.CullMode, (int)Cull.Counterclockwise);
DeviceManager.SetRenderState(RenderState.StencilEnable, 0);
DeviceManager.SetRenderState(RenderState.AlphaBlendEnable, 0);
DeviceManager.SetRenderState(RenderState.ColorWriteEnable, 0);


// draw shadow casting geometry
...

// get the effect
ID3DXEffect *pFX = GetFX();

// set the shadow map depth/stencil texture
pFX->SetTexture(GetShadowMapDSTexture());

// in pixel shader sample shadow map...
?

The problem is that the depth/stencil texture is a D24SX format…How do I sample from a texture of this format?

My original attempt which of course will not work:

tex2D(g_SamplerShadowMap, vShadowMapUV);

I read a post here that says:

When reading from the texture, one extra component in texture
coordinates will be the depth to compare with.

Or, how do I convert the color returned from the sampler code above to a single floating point value? The above code will return a 4-component vector but depth should be one value for comparison.

EDIT:

Below is the vertex shader for the shadow map pass…I do not compile a pixel shader for the shadow map pass because color is not written…only depth.

//--------------------------------------------------------------//
// ShadowMap Pass
//--------------------------------------------------------------//
void VS_ShadowMap( in float4 Position : POSITION0, 
                    out float4 oPos : POSITION0 )
{
    // position of geometry in the shadow emitting light's clip space
    oPos = mul(mul(Position, mW), g_mShadowViewProjection);
}

technique DeferredShading
{
    pass ShadowMap
    {
        VertexShader = compile vs_3_0 VS_ShadowMap();
        PixelShader = NULL;
    }   
}

Viewing all articles
Browse latest Browse all 69