Search code examples
c#openglopentk

OpenTK crashing as soon as I use OpenGL


I'm using OpenTK to make a C# OpenGL application.

I'm trying not to use the GameWindow class to open a context - here is my class managing a window + context :

using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Platform;
using OpenTK.Input;

class Window
{
    private INativeWindow window_;
    private IGraphicsContext context_;

    private bool isExiting_;

    public Window(int width, int height, bool fullscreen, string title = "StormEngine application")
    {
        window_ = new NativeWindow(width, height, title, fullscreen ? GameWindowFlags.Fullscreen : GameWindowFlags.FixedWindow, GraphicsMode.Default, DisplayDevice.Default);
        context_ = new GraphicsContext(GraphicsMode.Default, window_.WindowInfo, 4, 4, GraphicsContextFlags.Default);
        context_.MakeCurrent(window_.WindowInfo);
        window_.Visible = true;

        window_.KeyDown += (sender, e) =>
        {
            if (e.Keyboard[Key.Escape])
                window_.Close();
        };

        isExiting_ = false;
    }

    public Window(int width, int height) : this(width, height, false) { }

    public bool EndFrame()
    {
        context_.SwapBuffers();
        window_.ProcessEvents();
        return (window_.Exists && !isExiting_);
    }
}

I'm then calling Window w = new Window(800, 480); to open a window.

But as soon as I make a call to an OpenGL method, in my case int programId = GL.CreateProgram();, I am given a AccessViolationException.

My guess is that OpenGL function pointers are not loaded correctly, but I cannot find where the problem happens (I get no information about what happens inside GL.CreateProgam()).

Any idea of what might be happening, why, and how to resolve that ? :)


Solution

  • Forget it, I found my mistake :)

    In OpenTK, a GraphicsContext needs, once created and made current, to be loaded. To do so, just after context_.MakeCurrent(window_.WindowInfo);, I added :

    (context_ as IGraphicsContextInternal).LoadAll()
    

    I had to figure it out from the GameWindow class source on Github, tho, because this way to create a window isn't documented at all ^^

    And it now works like a charm. :)