为什么 Gl.Ortho() 抛出异常,我该如何解决?

Why is Gl.Ortho() throwing an exception and how do I fix it?

我正在编写 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() 抛出异常。怎么回事?

的实际调用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中解释过了。