为什么Gl.Ortho()抛出一个异常,我该如何修复呢?

时间:2017-08-03 14:51:14

标签: c# opengl windows-forms-designer

我正在编写一个C#Windows窗体应用程序。我正在使用来自NuGet包的OpenGL.Net和OpenGL.Net Win Forms v0.5.2。我在表单中添加了一个glControl。我试图在进入任何有趣的事情之前正确设置它。

这是glControl的加载事件

    private void glControl1_Load(object sender, EventArgs e)
    {
        //Initialize Here
        Gl.ClearColor(0.0f, 0.0f, 1.0f, 1.0f);
    }

这是glControl的渲染事件

    private void glControl1_Render(object sender, GlControlEventArgs e)
    {
        //Clear first
        Gl.Clear(ClearBufferMask.ColorBufferBit);

        Gl.MatrixMode(MatrixMode.Projection);
        Gl.PushMatrix();
        Gl.LoadIdentity();
        Gl.Ortho(0, glControl1.Width, 0, glControl1.Height, -1, 1);

        Gl.MatrixMode(MatrixMode.Modelview);
        Gl.PushMatrix();
        Gl.LoadIdentity();

        Gl.Enable(EnableCap.Texture2d);
        Gl.Enable(EnableCap.Blend);
        Gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);

        //Draw Here


        Gl.Disable(EnableCap.Blend);
        Gl.Disable(EnableCap.Texture2d);
        Gl.BindTexture(TextureTarget.Texture2d, 0);

        Gl.PopMatrix();
        Gl.MatrixMode(MatrixMode.Projection);
        Gl.PopMatrix();

        Gl.Finish();
    }

我从调用Gl.Ortho()获得异常。如果我发表评论,我不会遇到任何运行时问题。

System.NullReferenceException occurred
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=OpenGL.Net
StackTrace:
at OpenGL.Gl.Ortho(Single l, Single r, Single b, Single t, Single n, Single f)
at AnimationTool.Form1.glControl1_Render(Object sender, GlControlEventArgs e) 
Project\AnimationTool\AnimationTool\Form1.cs:line 53
at OpenGL.GlControl.OnRender()
at OpenGL.GlControl.OnPaint(PaintEventArgs e)

我不明白我是如何进行openGL调用的,只有我的Gl.Ortho()会抛出异常。发生了什么事?

1 个答案:

答案 0 :(得分:1)

实际调用 Gl.Ortho指向glOrthof,这是一个OpenGL 1.0 ES命令。由于您有桌面GL上下文,因此未加载任何函数,因此NullReferenceException

要解决您的问题,只需使用正确的方法重载:

Gl.Ortho(0.0, (double)glControl1.Width, 0.0, (double)glControl1.Height, -1.0, 1.0);

项目wiki已经解释了这个问题。