我在网上关注一本关于如何开始使用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();