C# 尝试将对象空间中边界框的范围转换为屏幕空间

C# 尝试将对象空间中边界框的范围转换为屏幕空间,c#,opengl,opentk,C#,Opengl,Opentk,在主题中,我想将对象空间中的3d点转换为屏幕空间。我已经花了好几天时间在网上阅读一些解决方案来解决这个问题,但我仍然有错误的结果。下面是我取得的最接近的结果: “屏幕空间”范围用红线表示,这显然是错误的。顶点的位置应与此处相同(请看蓝色线条): 有我的功能将对象转换为屏幕: public Vector2 WorldToScreen( Vector3 pos, int width, int height) { var pos4 = Vector4.Transform (new

在主题中,我想将对象空间中的3d点转换为屏幕空间。我已经花了好几天时间在网上阅读一些解决方案来解决这个问题,但我仍然有错误的结果。下面是我取得的最接近的结果:

“屏幕空间”范围用红线表示,这显然是错误的。顶点的位置应与此处相同(请看蓝色线条):

有我的功能将对象转换为屏幕:

public Vector2 WorldToScreen( Vector3 pos, int width, int height) {

        var pos4 = Vector4.Transform (new Vector4 (pos, 1), modelViewMatrix*projectionMatrix);

        var NDCSpace=pos4.Xyz/pos4.W;
        return new Vector2(NDCSpace.X*(width/2f),NDCSpace.Y*(height/2f));
    }
以下是设置项目的func和摄像头的modelView矩阵:

public void SetProjectionMatrix()
 {
    projectionMatrix  = Matrix4.CreatePerspectiveFieldOfView((float)(FieldOfView * Math.PI / 180.0), AspectRatio, ZNear, ZFar);
}

  public void SetModelviewMatrix()
 {
     var translationMatrix = Matrix4.CreateTranslation(-entityObject.position);
             var rotationMatrix = Matrix4.CreateFromQuaternion(ToQuaterion(entityObject.rotation));
        //modelViewMatrix = rotationMatrix*translationMatrix; orbit 
             modelViewMatrix = translationMatrix*rotationMatrix; //pan
}
在我看来,NDCSpace似乎返回了正确的值(-1..1,当完全位于视图截锥体内部时),所以我认为错误在于使用最终矩阵变换渲染部分。这是我绘制屏幕空间范围的函数。对于图形调试信息,我使用即时模式。(别担心,对于网格,我使用VBO)

最后一个想法是尝试使用广告牌矩阵,但没有成功。不过,我并没有对这个想法进行广泛的测试,不确定这在这种情况下是否有效

有人能帮我吗

编辑: 这是一个长方形

public static void DrawRectangle(Vector3 pos1, Vector3 pos2){

        GL.Begin(PrimitiveType.LineLoop);
        GL.Vertex3(pos1.X, pos1.Y,pos1.Z);
        GL.Vertex3(pos1.X, pos2.Y,pos1.Z);
        GL.Vertex3(pos2.X, pos2.Y,pos2.Z);
        GL.Vertex3(pos2.X, pos1.Y,pos2.Z);
        GL.Vertex3(pos1.X, pos1.Y,pos1.Z);
        GL.End ();
    }
这里是模型矩阵,这是网格模型矩阵

public void SetModelMatrix(){
        mesh.ModelMatrix=Matrix4.CreateScale(entityObject.scale)*Matrix4.CreateRotationX(entityObject.rotation.X) * Matrix4.CreateRotationY(entityObject.rotation.Y) * Matrix4.CreateRotationZ(entityObject.rotation.Z) *Matrix4.CreateTranslation(entityObject.position) ;
    }

旋转是以度为单位的

我对你对NDC的转换有点困惑。它应该是ProjMat*ModelView*PosVector。这就是发生的事吗?另外,您不需要指定要推送到哪个矩阵堆栈吗?在绘制立即模式时,您不也需要modelmatrix吗?这些是我能想出的唯一吹毛求疵的办法。祝你好运。我用的是Opentk,它是opengl绑定,但是!矩阵变换的一个主要区别是opentk使用directx表示法,即最后应用投影矩阵。我在即时模式下尝试了model*ortho matrix这似乎部分解决了Y,但Y有一些错误(屏幕Y与范围的世界Y不完全匹配),而X仍然完全错误。稍后我会发布截图你使用了什么样的模型矩阵?另外,DrawHelper.DrawRectangle做什么?你能显示代码吗?附加信息已经添加了chech edit section作为说明,当绘制矩形时,你的模型矩阵应该是标识矩阵。虽然我不确定错误是什么,但您的代码似乎与我以前的做法相当。
public void SetModelMatrix(){
        mesh.ModelMatrix=Matrix4.CreateScale(entityObject.scale)*Matrix4.CreateRotationX(entityObject.rotation.X) * Matrix4.CreateRotationY(entityObject.rotation.Y) * Matrix4.CreateRotationZ(entityObject.rotation.Z) *Matrix4.CreateTranslation(entityObject.position) ;
    }