Hot questions for Using Lightweight Java Game Library in glfw

Question:

I currently coding a Project using LWJGL 3. Since GLFW 3.2 its possible to add a window icon. I used it like you can see below, but I keep getting the error, and I have no clue why. What am I doing wrong?

What I have tried already:

  • I have made sure that the file is present in "res/img/icon.png".

  • The PNGLoader (Found here) works, as I am using textures and it loads them without any problems.

Code:

PNGDecoder dec = null;
try {
    dec = new PNGDecoder(new FileInputStream("res/img/icon.png"));
    int width = dec.getWidth();
    int height = dec.getHeight();
    ByteBuffer buf = BufferUtils.createByteBuffer(width * height * 4);
    dec.decode(buf, width * 4, PNGDecoder.Format.RGBA);
    buf.flip();
    Buffer images = new Buffer(buf);
    GLFW.glfwSetWindowIcon(window, images);
} catch (IOException e) {
    e.printStackTrace();
}

Here's the error that I get:

[LWJGL] GLFW_PLATFORM_ERROR error
    Description : Win32: Failed to create RGBA bitmap
    Stacktrace  :
        org.lwjgl.glfw.GLFW.nglfwSetWindowIcon(GLFW.java:1802)
        org.lwjgl.glfw.GLFW.glfwSetWindowIcon(GLFW.java:1829)
        ch.norelect.emulator.designer.Designer.initialize(Designer.java:81)
        ch.norelect.emulator.designer.Designer.start(Designer.java:48)
        ch.norelect.emulator.Main.main(Main.java:27)

Answer:

You are passing the raw pixel data as a GLFWImage.Buffer, but GLFW needs the width and height as well. GLFWImage.Buffer is just a convenience class for putting several GLFWImages next to each other, which each hold properties about an image.

GLFWImage image = GLFWImage.malloc();
image.set(width, height, buf);
GLFWImage.Buffer images = GLFWImage.malloc(1);
images.put(0, image);

glfwSetWindowIcon(window, images);

images.free();
image.free();

Question:

I am trying to call GLFW.glfwPollEvents() in an asynchronous task that runs every tick (1/30th of a second in this case). This ticking timer effectively controls when every action in the app takes place.

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run(){
        //... more code ...

        GLFW.glfwPollEvents();

        //... more code ...
    }
}, 33, 33);

But, this does not work because

This function may only be called from the main thread.

(from the documentation)

How can I call this on the main thread? When it isn't run on the main thread, the application crashes. I'm looking for something like

GLFW.dispatchMainThread(new GLFWRunnable(){
    public void run(){
        //...
    }
});

This is possible to do in swing and awt by using

EventQueue.invokeLater(new Runnable(){
    public void run(){
        //...
    }
});

But the same code doesn't work for GLFW.

How can I run a task on GLFW's main thread using LWJGL without using a while(true) loop on the main thread?


Answer:

Since GLFW's main thread must be the same as the application's main thread (a limitation in GLFW; that's where it puts the OS message queue that is handled differently by swing/awt it seems - see my answer here) I would do things the other way around.

My main thread would have the forever loop (probably using glfwWaitEvents so as not to eat CPU time needlessly). I would then post any events that were app-specific to another thread that does the processing. Your message processing is now decoupled from your message receiving.

This way I don't have to wait for 1/30th of a second to get OS messages (it always frustrates me when an app lags opening a menu, registering a click, or arrowing through a list).

Your update thread can even sleep for 1/30th of a second (or less, sleeping again if not enough time has passed or not if a second high-priority queue needs work) and only wake up to check for queued events as an extremely simple scheduling method.

The answer I linked to above has a link to an LWJGL Multithreaded Demo that does something very similar. Their renderLoop would be your updateLoop and would draw from a queue and do processing before going to sleep again instead of updating and presenting graphics.

Question:

I'm really starting out with LWJGL (I just started) and I focused on one thing: When I create a window and I want to set it as not resizable, I use:

glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);

However, even if I want to set this after the window was created, I do not know how. I just tried to put the command after the creation of the window, but it won't work:

window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

So, how I can resolve this?


Answer:

From the GLFW Window Guide:

Window creation hints

There are a number of hints that can be set before the creation of a window and context. Some affect the window itself, others affect the framebuffer or context. These hints are set to their default values each time the library is initialized with glfwInit, can be set individually with glfwWindowHint and reset all at once to their defaults with glfwDefaultWindowHints.

Note that hints need to be set before the creation of the window and context you wish to have the specified attributes.

Essentially, you set hints like whether the window should be resizable, which context version it has etc. through glfwWindowHint() calls. These hints will then be used the next time you create a window with glfwCreateWindow(). If you set hints after the window has been created, then only new windows created after the call will be affected.

Therefore, it is currently not possible to change certain GLFW window properties, like whether it is resizable, after creation.

Question:

I'm currently following a tutorial that has the initialization code to create the window

private void init() {
    // Setup an error callback. The default implementation
    // will print the error message in System.err.
    errorCallback = GLFWErrorCallback.createPrint(System.err);
    glfwSetErrorCallback(errorCallback);

    // Initialize GLFW. Most GLFW functions will not work before doing this.
    if (!glfwInit()) {
        throw new IllegalStateException("Unable to initialize GLFW");
    }

    // Configure our window
    glfwDefaultWindowHints(); // optional, the current window hints are already the default
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // the window will stay hidden after creation
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); // the window will be resizable

    int WIDTH = 300;
    int HEIGHT = 300;

    // Create the window
    window = glfwCreateWindow(WIDTH, HEIGHT, "Hello World!", NULL, NULL);
    if (window == NULL) {
        throw new RuntimeException("Failed to create the GLFW window");
    }

    // Setup a key callback. It will be called every time a key is pressed, repeated or released.
    glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() {
        @Override
        public void invoke(long window, int key, int scancode, int action, int mods) {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
                glfwSetWindowShouldClose(window, true); // We will detect this in our rendering loop
            }
        }
    });

    // Get the resolution of the primary monitor
    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    // Center our window
    glfwSetWindowPos(
            window,
            (vidmode.width() - WIDTH) / 2,
            (vidmode.height() - HEIGHT) / 2
    );

    // Make the OpenGL context current
    glfwMakeContextCurrent(window);
    // Enable v-sync
    glfwSwapInterval(1);

    // Make the window visible
    glfwShowWindow(window);
}

Notice the glfwWindowHint(GLFW_VISIBLE, GL_FALSE); hint is disabled, then after creating the window, setting the key callbacks, binding the opengl context, it's enabled again glfwShowWindow(window);

The documentation doesn't suggest doing anything like this, and removing both lines doesn't seem to change anything. Why disable the hint in the first place?

Tutorial: https://lwjglgamedev.gitbooks.io/3d-game-development-with-lwjgl/content/chapter1/chapter1.html


Answer:

It disables visablity so it can set up the size, change position, and initialize the context without the client having to witness it. From the Window Visablity section in the GLFW docs:

Windowed mode windows can be created initially hidden with the GLFW_VISIBLE window hint. Windows created hidden are completely invisible to the user until shown. This can be useful if you need to set up your window further before showing it, for example moving it to a specific location.

Youre program follows that exact example by calling

glfwSetWindowPos(
            window,
            (vidmode.width() - WIDTH) / 2,
            (vidmode.height() - HEIGHT) / 2
    );

Question:

I'm using glfw 3.2 with LWJGL and Java.

I'd like to remove the maximize, and minimize button on my windows while the window remains resizable, and I can't find any way to do that in the glfw documentation.

I've seen this solution but it only works on windows, and with C++, the solution I'm looking for needs to be cross platform.

Is it possible to achieve this using glfw? Or should I use an undecorated glfw window and draw my own title bar?


Answer:

There is no way of achieving that with GLFW 3.2

Question:

I've been doing some benchmarking on my game-engine and found a foul culprit:

glfwPollevents();

I've timed this thoroughly and 95% of the time it behaves as expected, but sometimes it eats 5-200% of my update interval (which is 1/60 second). I have literally no idea what's causing this. During these immense polls, no of my defined callbacks are called. Everything is quiet and still. It's completely unpredictable.

I've got a few theories: 1. the scheduler interrupts somewhere within the function. This would be very unlikely, and I would see the same behaviour in other parts of my loops, which I don't.

  1. There's some evil callback that I don't know about somewhere that's beeing called and eats time.

  2. lwjgl problems. LWJGL is a wrapper from glfw, so that it can be used in Java, which I do.

  3. drivers, but which?


Answer:

glfwPollEvents(); is a wrapper for the OS-specific system call that enables you to check for any events applied to the window. There are a lot of things that count as events, including user-level stuff like selecting or resizing the window, but also including System-level stuff that GLFW doesn't give you access to. There's any number of things that could cause brief interrupts/hangs like you're describing.

Generally speaking, the best advice is to handle rendering on a different thread, and use a message queue to instruct the main thread to perform "main thread critical tasks" (like opening a new window or other similarly important tasks).

Question:

I am trying to port this tutorial to Kotlin/Java with LWJGL3 using the "modern" OpenGL versions. I have followed this tutorial in c++, where I managed to create a coloured cube, that was rotated. Because I am not as familiar with c++, I made the decision to swap to Java/Kotlin.

I am unable to find the glewInit() function in LWJGL3 and all the other stuff around GLEW. From what I have read, with glew I can access the modern OpenGL API.

I have looked up some LWJGL3 tutorials, but I was unable to find one with the modern OpenGL syntax.

I have also read this question where, the answer seemed to me like LWJGL3 is basically GLEW for Java.

So is it true that I must access GLEW in order to write a "modern" OpenGL application? And if so, how with LWJL3? Or is LWJGL3 the replacement for GLEW in Java?


Answer:

GLEW is an OpenGL function loading library. It's purpose is to allow you to access OpenGL, as provided by your implementation. This is important for programs written in C and C++, and GLEW is very much a C library.

LWJGL performs essentially the same function for Java. It also does other things that GLEW doesn't (like managing the OpenGL window, etc).

So in Java, you don't need GLEW, and can't really use it even if you did.

Question:

I've compiled the Get Started example from the lwjgl.org webpage (http://www.lwjgl.org/guide) and now I wanted to continuously change to background-color. So, I wanted something like a blinking effect. But I don't get the background to switch its color permanently with glClearColor, when the program is running. I've tried to do this in the loop() function in the while loop with glClearColor. But that seems wrong, as the glClearColor Method is only called outside the while loop. For instance in the following code, the background color takes the color that was lastly called with glClearColor.

...
 private void loop() {
    // 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 ContextCapabilities instance and makes the OpenGL
    // bindings available for use.
    GLContext.createFromCurrent();



    // Set the clear color
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    // Run the rendering loop until the user has attempted to close
    // the window or has pressed the ESCAPE key.
    while ( glfwWindowShouldClose(window) == GL_FALSE ) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

        /* Switch permanently between red and green background color
            - doesn't work, no blinking, just green background color */ 
        glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

        glfwSwapBuffers(window); // swap the color buffers

        // Poll for window events. The key callback above will only be
        // invoked during this call.
        glfwPollEvents();
    }
}
...

I'm very new to lwjgl, thus I think I'm making some basic mistake and the background color shouldn't be changed in that way I did at all. Is there something to handle the background in lwjgl to achieve this?

I should mention that I'm using lwjgl 3, not lwjgl 2. And it seems to be that there is no Display Class anymore. GLFW seems to be the replacement for that.


Answer:

In the while loop below, think that each iteration represent your 1 frame. In your scene you will see a change only after glfwPollEvents() call after each iteration. That's why changing color 2 times at one iteration won't affect anything.

while ( glfwWindowShouldClose(window) == GL_FALSE ) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

    /* Switch permanently between red and green background color
        - doesn't work, no blinking, just green background color */ 
    glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
    glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

    glfwSwapBuffers(window); // swap the color buffers

    // Poll for window events. The key callback above will only be
    // invoked during this call.
    glfwPollEvents();
}

At below, I wrote a simple solution for your problem. If you change the color at every frame you cannot see the change because it will be very fast, so I did a small trick that change your color at every 30 frame. You can write an alternative using time dependent color change instead of frame count.

Correct Version:

boolean redOrGreen = true; // true = Green false = Red
int  counter = 0;
int  COLORCHANGEAT = 30;

while ( glfwWindowShouldClose(window) == GL_FALSE ) {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

    counter++;
    if(counter == COLORCHANGEAT) {      
       redOrGreen = !redOrGreen;
       counter = counter % COLORCHANGEAT;
    }

    if(redOrGreen == true)
       glClearColor(1.0f, 1.0f, 0.0f, 0.0f);
    else        
       glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

    glfwSwapBuffers(window); // swap the color buffers

    // Poll for window events. The key callback above will only be
    // invoked during this call.
    glfwPollEvents();
}

Question:

I'm learning LWJGL for the first time and exploring a simple code block given as an example on the LWJGL3 site. I have never used OpenGL or GLFW before neither.

I don't understand this small chunk of code. If I remove it, the main code still works. Is this whole thing only to center the window upon creation?

What is mallocInt (1) supposed to mean? This whole idea of stackPush() and strange method calls has be confused. I have used SWT and awt and never seen anything like it.

// Get the thread stack and push a new frame

try ( MemoryStack stack = stackPush() ) {

    IntBuffer pWidth = stack.mallocInt(1); // int*
    IntBuffer pHeight = stack.mallocInt(1); // int*

    // Get the window size passed to glfwCreateWindow
    glfwGetWindowSize(window, pWidth, pHeight);

    // Get the resolution of the primary monitor
    GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    // Center the window
    glfwSetWindowPos(window,
        (vidmode.width() - pWidth.get(0)) / 2,
        (vidmode.height() - pHeight.get(0)) / 2);

}

// the stack frame is popped automatically

Any help is much appreciated.


Answer:

LWJGL allows memory allocations on the stack at speed much faster than pure Java allows through the MemoryStack class. In order to get the stack, you call stackPush(). By putting it in the try clause as you have done, it makes it so the stack allocation is thread local and the stack is popped and buffers are freed once the try statement is done.

MemoryStack.mallocXX(count) (where xx is the type and count is the size of the buffer) is how one goes about allocating from the stack. stack.mallocInt(1) returns an integer buffer of size one from the stack, instead of from the heap.

In general, when you are doing uniforms or anything where you need a buffer, use MemoryStack.stackPush(). LWJGL has a very good article (here) about the different methods of memory management in LWJGL3, and I definitely recommend taking the time to sit down and learn these new memory techniques.

Question:

I'm creating a Game Engine that works with LWJGL 3. I'm creating a class named 'FrameManager' wish handle Window inputs (Like Size, Position, etc) but I've looked for in many web sites, documentation etc, and I didn't find how to create a simple method wish set the Window icon. First, I found a GLFW 3 method: glfwSetWindowIcon(frameId, images); But it don't seems to work on macOS Sierra 1.12 (I cannot test on Window for the moment). Here is how i use this method:

                log.debug(" -> Setting Icon...");
                final PNGDecoder decoder = new PNGDecoder(new FileInputStream(iconPath));
                final int iconWidth = decoder.getWidth();
                final int iconHeight = decoder.getHeight();
                final ByteBuffer buffer = createByteBuffer(iconWidth * iconHeight * 4);
                decoder.decode(buffer, iconWidth * 4, PNGDecoder.Format.RGBA);
                buffer.flip();
                final GLFWImage image = malloc();
                image.set(iconWidth, iconHeight, buffer);
                final GLFWImage.Buffer images = malloc(1);
                images.put(0, image);

                glfwSetWindowIcon(frameId, images);

                images.free();
                image.free();

I tried it before/after Window Creation/Show but nothing happen in macOS Sierra 10.12 (No Error, but no Icon).

So, i considered that it works on Window but not on Mac.

I looked for an Apple solution, than I found 2 ways, but it doesn't work :( First, adding this in the VM launch args: -Xdock:icon=/path/myIcon.png But nothing happen :( And I also tried that:

Application.getApplication().setDockIconImage(Image img);

It doesn't create an icon and interrupt the Thread (Thread is blocked at this moment).

I known that Application Bundle exists, but is-there really no other solution ?

Thanks for your help! Have a nice day!


Answer:

According to the GLFW documentation the GLFW icon API does not work, see the "Remarks" in the API documentation.

It mentions that you should use the bundles icon to set the dock bar icon.

Question:

I'm developing a game with java and LWJGL3. But I don't understand how to fix my problem, I've tried to search on the internet but the information for LWJGL is minimal and I couldn't find anything for GLFW.

Let's say for example I have a menu with 4 buttons (new game, options, credits, exit) and a count variable to know which one is selected. Every time the up arrow key is pressed I want to subtract one from the select, to select the previous one, and the same for the down arrow key, but I want to add one.

The problem is the following: if in the frame 0 I press the arrow key the count variable is added but in the next frame the key is still pressed, so it is added again. I don't know how to fix this, I tried to changing GLFW_PRESS to GLFW_RELEASE, but I want the action to happen when the key was pressed.

if ((glfwGetKey(window, GLFW_KEY_UP) == GLFW_REPEAT) && select > 0) {
    button[select].toggleSelect();
    select--;
    button[select].toggleSelect();
}

if ((glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_REPEAT) && select < button.length) {
    button[select].toggleSelect();
    select++;
    button[select].toggleSelect();
}

I know that this code can throw an array index out of bounds exception


Answer:

You should register a key callback:

private GLFWKeyCallback keyCallback;

// ...

keyCallback = new GLFWKeyCallback() {
    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {
        if (action == GLFW_PRESS) {
            if (key == GLFW_KEY_UP && /*...*/) {
                // ...
            }
            if (key == GLFW_KEY_DOWN && /*...*/) {
                // ...
            }
        }
    }
}
glfwSetKeyCallback(window, keyCallback);

The invoke() method will be called every time a key event is generated. The action parameter can take three values:

  • GLFW_PRESS when the key was just pressed
  • GLFW_REPEAT afterwards, when the key is still being pressed
  • GLFW_RELEASE when the key wast just released

While glfwGetKey() returns only GLFW_PRESS or GLFW_RELEASE, the key callback only uses GLFW_PRESS the first time the key is being pressed and GLFW_REPEAT afterwards, allowing you to differentiate between the first frame during which the key is pressed and subsequent ones.

Question:

I am trying to create a program with LWJGL and OpenGL 3. However, when my code gets to the following line:

program = glCreateProgram();

My program exits with the following output:

Version.getVerson() => 3.1.2 build 29
glfwInit() => true
glfwCreateWindow() => long
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007faa30c86a67, pid=15863, tid=0x00007faa5a409700
#
# JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [liblwjgl_opengl.so+0x43a67]  Java_org_lwjgl_opengl_GL20_glCreateProgram+0x7
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/tague/IdeaProjects/Jaav/hs_err_pid15863.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

I tried to add this line to my code, directly after my glfwMakeContextCurrent:

System.out.println("glGetString(GL_VERSION) => " + glGetString(GL_VERSION));

But now, the program simply exits with a segfault there instead.

I am using the following GLFW window hints:

glfwDefaultWindowHints();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);  // Hide window at the start.
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // Window is resizable.

Edit: Here's the complete program, excluding things that aren't being called.

Main.java:

package me.tague.jaav;

import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;

import java.nio.*;

import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;

public class Main {

    public long window;
    private Mesh main;

    // Run the actual LWJGL app.
    public void run () {
        System.out.println("Version.getVerson() => " + Version.getVersion());

        init();

        // System.out.println("glGetString(GL_VERSION) => " + glGetString(GL_VERSION)); // <=== ANOTHER SOURCE OF THE ERROR!!! 

        float[] mainVerts = {
                -0.5f, -0.5f, 0.0f,
                0.5f, -0.5f, 0.0f,
                0.0f,  0.5f, 0.0f
        };
        main = new Mesh(mainVerts);

        // ...
    }

    private void init () {
        // Print GLFW errors to System.err.
        GLFWErrorCallback.createPrint(System.err).set();

        // Set up GLFW.
        if (!glfwInit()) throw new IllegalStateException("glfwInit() => false");
        else System.out.println("glfwInit() => true");

        glfwDefaultWindowHints();

        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);  // Hide window at the start.
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // Window is resizable.

        // Create the window.
        window = glfwCreateWindow(1024, 768, "Hello!", NULL, NULL);
        if (window == NULL) throw new RuntimeException("glfwCreateWindow() => NULL");
        else System.out.println("glfwCreateWindow() => long");

        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
                glfwSetWindowShouldClose(window, true);
        });

        try (MemoryStack stack = stackPush()) {
            IntBuffer pWidth = stack.mallocInt(1);
            IntBuffer pHeight = stack.mallocInt(1);

            glfwGetWindowSize(window, pWidth, pHeight);

            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            // Center the window
            glfwSetWindowPos(
                    window,
                    (vidmode.width() - pWidth.get(0)) / 2,
                    (vidmode.height() - pHeight.get(0)) / 2
            );
        }

        glfwMakeContextCurrent(window);
        glfwSwapInterval(-1);
        glfwShowWindow(window);
    }

    public static void main(String[] args) {
        new Main().run();
    }
}

Mesh.java:

package me.tague.jaav;

import org.lwjgl.BufferUtils;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;

import java.nio.FloatBuffer;

public class Mesh {

    public Material material;

    public Mesh(float[] vertices) {
        // Set up a default, generic material.
        material = new Material();

        // ... some more stuff that isn't called yet.
    }
}

Material.java:

package me.tague.jaav;

import java.io.*;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;

public class Material {
    private int program;

    public Material () {
        makeProgram("shaders/generic/vert.gl", "shaders/generic/frag.gl");
    }

    /**
     * Make an OpenGL Program, given vertex and fragment source files.
     * @param vert The filename for the vertex shader to use.
     * @param frag The filename for the fragment shader to use.
     * @return     The ID for the loaded program.
     */
    private void makeProgram(String vert, String frag) {
        // Create the program in OpenGL.
        program = glCreateProgram(); // <==== THE SOURCE OF THE ERROR !!!!!

        // ... more stuff that never runs
    }    
}

Answer:

I found a solution: I was missing GL.createCapabilities() in my init. This function is required before any gl* calls are made.

Question:

I'm learning how to make a Java game with ThinMatrix's LWJGL 2 tutorials that I'm adapting to LWJGL 3. Anyway, I can't get the game to detect my monitors. This was working fine just a few days ago on the exact same system with the exact same hardware.

I have tried installing the drivers for them, uninstalling the drivers, and uninstalling the monitors completely from Device Manager. Nothing works. If you need any more information just let me know!

Here is my source code:

Main.java:

package engineTest;

import static org.lwjgl.glfw.GLFW.*;

import static renderEngine.displayManager.*;

public class Main {

    public static void main(String[] args) {

        window = glfwCreateWindow(WIDTH, HEIGHT, "Farm Game", glfwGetPrimaryMonitor(), 0);

        while(!glfwWindowShouldClose(window)) {

            updateDisplay();

        }

        glfwDestroyWindow(window);

    }

}

displayManager.java

package renderEngine;

import static org.lwjgl.glfw.GLFW.*;

import org.lwjgl.opengl.GL11;

public class displayManager {

    public static int WIDTH = 1280;
    public static int HEIGHT = 720;
    private static int FPS_CAP = 120;

    public static long window;

    public static void createDisplay() {

        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

        GL11.glViewport(0, 0, WIDTH, HEIGHT);
    }

    public static void updateDisplay() {

        glfwPollEvents();
        glfwSwapBuffers(FPS_CAP);

    }

    public static void closeDisplay() {

        glfwDestroyWindow(window);

    }

}

Here is the error output.

Exception in thread "main" java.lang.NullPointerException
   at org.lwjgl.system.Checks.check(Checks.java:99)
   at org.lwjgl.glfw.GLFW.glfwWindowShouldClose(GLFW.java:1874)
   at engineTest.Main.main(Main.java:13)
Edit

I have been trying to debug the NullPointerException, and I know what is causing it. The problem is I don't know how to fix it. Sorry, I'm pretty new to Java.


Answer:

You have to call glfwInit() before you can use any other glfw method. Since this is missing, glfwCreateWindow always returns a nullptr.

Question:

LWJGL version: 3.1.4 build 8 GLFW version: 3.3.0 Win32 WGL EGL VisualC DLL

The controller shows up in the device manager as Xbox Controller under Xbox Peripherals and seems to be working fine in games.

However, trying glfwJoystickPresent() only returns false:

for (int joy = GLFW_JOYSTICK_1; joy<=GLFW_JOYSTICK_LAST;joy++) {    
    System.out.println(joy+": "+glfwJoystickPresent(joy))
}

Is the Xbox One controller not supported? Is there faulty hardware at play? Is there anything else I'm missing?

Edit: This is my complete code:

import static org.lwjgl.glfw.GLFW.*;

public class FuckingControllerInput {
    public static void main(String[] args) {        
        System.out.println(Version.getVersion());
        System.out.println(glfwGetVersionString());
        for (int joy = GLFW_JOYSTICK_1; joy<=GLFW_JOYSTICK_LAST;joy++) {
            System.out.println(joy+": "+glfwJoystickPresent(joy));
        }       
    }
}

Answer:

XBox controllers should be supported, there were some conversations here talking about it

http://www.java-gaming.org/topics/glfw-controller-database/37754/view.html

With out you posting any other code or providing more details of your controller it is hard to tell what is wrong. Try the controller test program in the link to see if you get recognition of your controller. Other people definitely have had luck with xbox controllers.