Search code examples
nullpointerexceptionkotlinlwjgl

NPE When Using glfwWindowShouldClose (Kotlin)


So I've just started on a basic LWJGL 3 program using this tutorial. I've converted all the code into Kotlin to make it work, and everything seemed to be fine. Until I got to the very end where he utilizes glfwWindowShouldClose(window). I tried it the way he showed, and my own method of replacing the running variable with the function call itself. I even tried replacing it with true. Unfortunately, it doesn't appear to be working.

To clarify, what I mean is that when I use glfwWindowShouldClose(window) anywhere in my project, any call to an LWJGL function results in an NPE, even functions that have nothing to do with it:

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)

The code I used for this example of the error is here:

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) }
}

If I remove the function call and replace it with false in the while statement, it works fine. Is it possible that the instance of my loop itself is causing problems, and the only way it doesn't throw an exception is if the loop never happens (false)?


Solution

  • You are missing some important calls, such as GL.createCapabilities()

    I'd strongly suggest you to start from the HelloWord you find here

    Ps: if you use kotlin, I have a lib that can give you a ready scenario in a couple of lines

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