Directx 3D the farther object covers the nearer object

46 views Asked by At

I'm new to the DirectX in c#, and there is a question that confused me a lot, basically I want to render two cubes on the screen, one is near from the camera and the other is far from the camera, what I expected is the nearer one always in front of the further one, but in fact, it depends on the rendering sequence, the last rendered one always in front of the other, I've tried to clear the z-buffer but that does not work at all, so I'm wondering if there is something I'm doing wrong?

Here are my code snippet

private void Form1_Load(object sender, EventArgs e)
    {
        PresentParameters presentParams = new PresentParameters();
        presentParams.Windowed = true;
        presentParams.SwapEffect = SwapEffect.Discard;
        presentParams.EnableAutoDepthStencil = true;
        presentParams.AutoDepthStencilFormat = DepthFormat.D16;

        device = new Device(0, DeviceType.Hardware, this, CreateFlags.MixedVertexProcessing, presentParams);
        device.VertexFormat = CustomVertex.PositionColored.Format;
        device.RenderState.CullMode = Cull.CounterClockwise;
        device.RenderState.Lighting = false;

        Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0f, 10000.0f);
        device.Transform.Projection = projection;
    }

protected override void OnPaint(PaintEventArgs e)
    {
        Cube a = new Cube(new Vector3(0, 0, 0), 5);
        Cube b = new Cube(new Vector3(0, 0, 15), 5);
        device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkGray, 1, 0);
        device.BeginScene();
        Matrix viewMatrix = Matrix.LookAtLH(cameraPosition, targetPosition, up);
        device.Transform.View = viewMatrix;
        device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, 8, 12, a.IndexData, false, a.GetVertices());
        device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, 8, 12, b.IndexData, false, b.GetVertices());
        device.EndScene();
        device.Present();
    }
1

There are 1 answers

1
Edgar On

Alright, I finally fixed the problem, by changing

Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 0f, 10000.0f);

to

Matrix projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 10000.0f);

But I don't know the reason, and why it happens, does anyone know that?