首页 > 解决方案 > 画框不正确

问题描述

我在绘制盒子形状时遇到问题(它很长)

长箱

创建矩阵的代码(其中宽度和高度是窗口的大小):

GL.Enable(EnableCap.DepthTest);
                GL.DepthMask(true);
                GL.DepthFunc(DepthFunction.Lequal);

                float aspect = (float)width / (float)height;

                matrix = Matrix4.CreateTranslation(0, 0, -100) * // 100 > 51 
                                 Matrix4.CreatePerspectiveOffCenter(-aspect, aspect, 1, -1, 1, 1000);

绘制框的代码:

public void Box(double w, double h, double d)
    {
        float x1 = (float)-w / 2f; float x2 = (float)w / 2f;
        float y1 = (float)-h / 2f; float y2 = (float)h / 2f;
        float z1 = (float)-d / 2f; float z2 = (float)d / 2f;

        var vertbuffer = new Vector3[]
        {
            // front
            new Vector3(x1, y1, z1),
            new Vector3(x2, y1, z1),
            new Vector3(x2, y2, z1),
            new Vector3(x1, y2, z1),

            // right
            new Vector3(x2, y1, z1),
            new Vector3(x2, y1, z2),
            new Vector3(x2, y2, z2),
            new Vector3(x2, y2, z1),

            // back
            new Vector3(x2, y1, z2),
            new Vector3(x1, y1, z2),
            new Vector3(x1, y2, z2),
            new Vector3(x2, y2, z2),

            // left
            new Vector3(x1, y1, z2),
            new Vector3(x1, y1, z1),
            new Vector3(x1, y2, z1),
            new Vector3(x1, y2, z2),

            // top
            new Vector3(x1, y1, z2),
            new Vector3(x2, y1, z2),
            new Vector3(x2, y1, z1),
            new Vector3(x1, y1, z1),

            // bottom
            new Vector3(x1, y2, z1),
            new Vector3(x2, y2, z1),
            new Vector3(x2, y2, z2),
            new Vector3(x1, y2, z2),
        };

        GL.EnableClientState(ArrayCap.VertexArray);
        GL.EnableClientState(ArrayCap.NormalArray);

        GL.VertexPointer(3, VertexPointerType.Float, Vector3.SizeInBytes, vertbuffer);
        GL.NormalPointer(NormalPointerType.Float, Vector3.SizeInBytes, normalBuffer);

        GL.Color4(fillColor);
        GL.DrawArrays(PrimitiveType.Quads, 0, vertbuffer.Length);

        GL.Color4(strokeColor);
        GL.LineWidth((float)strokeWeight);

        for (int i = 0; i < vertbuffer.Length / 4; i++)
        {
            GL.DrawArrays(PrimitiveType.LineLoop, i * 4, 4);
        }
    }

它看起来像前面的四边形没有绘制:

在此处输入图像描述

我试图减少的 depthFar 参数Matrix4.CreatePerspectiveOffCenter但这不起作用。

编辑:我已经更新了代码。

标签: c#openglopentk

解决方案


所有不在近平面和远平面之间的几何图形都将被剪裁。

你的立方体的大小是100、100、100。到近平面的距离是1,到远平面的距离是1000。
因此,相机和立方体中心之间的距离必须至少为51(d /2 + near = 100/2 +1),否则立方体的前部将被视锥体的关闭平面切断。

OpenGL坐标系是右手系。x 轴指向右侧,y 轴指向上方。z 轴由x 轴和 y 轴的叉积计算并指向视图外。因此,几何必须在负 z 方向上移动。

我建议对大小为 100x100x100 的立方体使用以下投影和平移:

float aspect = (float)width/(float)height;
matrix = Matrix4.CreateTranslation(0, 0, -100) * // 100 > 51
    Matrix4.CreatePerspectiveOffCenter(-aspect, aspect, 1, -1, 1, 1000);

推荐阅读