glMakeContextCurrent / glViewport 致命错误

glMakeContextCurrent / glViewport fatal error

我正在关注一本关于如何开始使用 GLFW 的在线书籍。作为参考,我使用 Java.

我按照本书的步骤编写了一些代码,但出现此错误:FATAL ERROR in native method: Thread[main,5,main]: No context is current or a function that is not available in the current context was called。我的代码如下:

import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL11;
import org.lwjgl.system.MemoryUtil;

public class Window {
    private long window;
    
    public Window()
    {
        
    }
    
    public void init()
    {
        GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3);
        GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 3);
        GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE);
        
        if(!GLFW.glfwInit())
        {
            throw new IllegalStateException("Could not initialize glfw");
        }
        
        window = GLFW.glfwCreateWindow(800, 600, "window", MemoryUtil.NULL, MemoryUtil.NULL);
        
        if(window == MemoryUtil.NULL)
        {
            throw new IllegalStateException("Could not initialize window");
        }
        
        GLFW.glfwMakeContextCurrent(window);
        
        GL11.glViewport(0, 0, 800, 600);
        
        GLFW.glfwSetFramebufferSizeCallback(window,  (window, width, height) -> {
            GL11.glViewport(0, 0, width, height);
        });
    }
    
    public void gameLoop()
    {
        while(!GLFW.glfwWindowShouldClose(window))
        {
            GLFW.glfwSwapBuffers(window);
            GLFW.glfwPollEvents();
        }
        
        GLFW.glfwTerminate();
    }
    
    public void cleanup() {
        GLFW.glfwDestroyWindow(window);
    }
}

我该如何解决这个错误?另外,如果我的代码结构不好,请告诉我。

谢谢!

GLFW.glfwMakeContextCurrent() 之后需要 GL.createCapabilities()

这个在官方示例代码中有提到(https://www.lwjgl.org/guide)

  // This line is critical for LWJGL's interoperation with GLFW's
  // OpenGL context, or any context that is managed externally.
  // LWJGL detects the context that is current in the current thread,
  // creates the GLCapabilities instance and makes the OpenGL
  // bindings available for use.
  GL.createCapabilities();