使用 glfwWindowShouldClose 时的 NPE(Kotlin)

NPE When Using glfwWindowShouldClose (Kotlin)

所以我刚刚开始使用这个 tutorial 的基本 LWJGL 3 程序。我已将所有代码转换为 Kotlin 以使其工作,一切似乎都很好。直到我走到最后他利用glfwWindowShouldClose(window)。我按照他展示的方式进行了尝试,并尝试了我自己用函数调用本身替换 running 变量的方法。我什至尝试用 true 替换它。不幸的是,它似乎没有用。

澄清一下,我的意思是当我在项目中的任何地方使用 glfwWindowShouldClose(window) 时,对 LWJGL 函数的任何调用都会导致 NPE,即使是与它无关的函数也是如此:

Exception in thread "thingy" java.lang.NullPointerException
    at org.lwjgl.system.Checks.check(Checks.java:98)
    at org.lwjgl.glfw.GLFW.glfwSwapBuffers(GLFW.java:4206)
    at main.Window.render(main.kt:39)
    at main.Window.run(main.kt:15)
    at java.lang.Thread.run(Thread.java:745)

我在这个错误示例中使用的代码在这里:

class Window: Runnable {
    private val thread = Thread(this, "thingy")
    private val window: Long

    override fun run() {
        while (true) {
            update()
            render()
        }
    }

    init { thread.start(); window = init() }

    private fun init(): Long {
        if (!glfwInit()) System.err.println("Couldn't initialize GLFW.")
        glfwWindowHint(GLFW_RESIZABLE, 1)
        val window = glfwCreateWindow(800, 600, "thingy", NULL, NULL)
        if (window == NULL) System.err.println("Couldn't create a window.")
        val vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor())
        glfwSetWindowPos(window, 100, 100)
        glfwMakeContextCurrent(window)
        glfwShowWindow(window)
        return window
    }

    private fun update() { glfwPollEvents() }

    private fun render() { glfwSwapBuffers(window) }
}

如果我删除函数调用并在 while 语句中将其替换为 false,它就可以正常工作。是否有可能是我的循环实例本身导致了问题,并且它不抛出异常的唯一方法是如果循环从不发生 (false)?

您错过了一些重要的电话,例如GL.createCapabilities()

我强烈建议您从找到的 HelloWord 开始 here

Ps:如果你使用 kotlin,我有一个 lib 可以在几行中给你一个现成的场景

with(glfw) {
   init()
   windowHint { context.version = "3.3"; profile = "core"; }
}
GlfwWindow(windowSize, title).apply { makeContextCurrent(); show(); }
GL.createCapabilities()