Background face is visible over foreground face in same mesh while using a diffuse shader in DirectX

StackOverflow https://stackoverflow.com/questions/22740621

  •  24-06-2023
  •  | 
  •  

Question

I am trying to create a simple diffuse shader to paint primitive objects in DirectX 9 and faced following problem. When I used a DirectX primitive object like a Torus or Teapot, some faces in the foreground part of the mesh is invisible. I don't think this is the same thing as faces being invisible as I cannot reproduce this behavior for primitive objects like Sphere or Box where no two quads have the same normal. Following are some screenshots in fill and wire-frame modes. torus fill-mode

Following is my vertex deceleration code.

// vertex position...
D3DVERTEXELEMENT9 element;
element.Stream = 0;
element.Offset = 0;
element.Type = D3DDECLTYPE_FLOAT3;
element.Method = D3DDECLMETHOD_DEFAULT;
element.Usage = D3DDECLUSAGE_POSITION;
element.UsageIndex = 0;
m_vertexElement.push_back(element);

// vertex normal
element.Stream = 0;
element.Offset = 12; //3 floats * 4 bytes per float
element.Type = D3DDECLTYPE_FLOAT3;
element.Method = D3DDECLMETHOD_DEFAULT;
element.Usage = D3DDECLUSAGE_NORMAL;
element.UsageIndex = 0;
m_vertexElement.push_back(element);

And shader code in development.

float4x4 MatWorld : register(c0);      
float4x4 MatViewProj : register(c4); 
float4 matColor : register(c0);

struct VS_INPUT
{
float4 Position   : POSITION;
float3 Normal : NORMAL;
};

struct VS_OUTPUT
{
float4 Position   : POSITION;
float3 Normal : TEXCOORD0;
};

struct PS_OUTPUT
{
float4 Color   : COLOR0;
};

VS_OUTPUT vsmain(in VS_INPUT In)
{
    VS_OUTPUT Out;

float4 wpos = mul(In.Position, MatWorld);

Out.Position = mul(wpos, MatViewProj);
Out.Normal = normalize(mul(In.Normal, MatWorld));

return Out;
};

PS_OUTPUT psmain(in VS_OUTPUT In)
{
PS_OUTPUT Out;
float4 ambient = {0.1, 0.0, 0.0, 1.0};
float3 light = {1, 0, 0};
Out.Color = ambient + matColor * saturate(dot(light, In.Normal));

return Out;
};

I have also tried setting different render states for Depth-Stencil but wasn't successful.

project files

Was it helpful?

Solution

I figure it out! this is a Depth Buffer(Z-Buffer) issue, you can enable Z-Buffer in your code, either by fixed pipeline or in the shader.

To enable z-buffer in fixed pipeline:

First add the following code when creating D3D deivce

d3dpp.EnableAutoDepthStencil = TRUE ;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16 ;

Then enable z-buffer before drawing

device->SetRenderState(D3DRS_ZENABLE, TRUE) ;

At last, clear z-buffer in render function

device->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top