Skip to content

Introduction

SilverTiger edited this page Dec 19, 2014 · 14 revisions

This is a simple quick starting guide for the new version of the Lightweight Java Game Library.

Setup LWJGL3

Downloading LWJGL3

  1. The very first step is of course downloading the library, you can get it here.
    Currently there is no release version, so get the stable or the nightly version.
  2. After that just extract the lwjgl.zip file to any location you want it to be.
  3. You should now have the folders doc, jar and native and a file src.zip.

Setting up your favorite IDE

Now that you have downloaded the library start up your IDE.

NetBeans

You have to do the following steps just once.

  1. Go to Tools -> Libraries
  2. Click on New Library
  3. Type any name for the library like LWJGL3
  4. Select the newly made library
  5. At the Classpath tab click on Add JAR/Folder... and go into the folder where you extracted the lwjgl.zip and go into the jar folder and select lwjgl.jar and disruptor.jar
  6. At the Source tab click on Add JAR/Folder... and go into the folder where you extracted the lwjgl.zip and select src.zip
  7. At the Javadoc tab click on Add ZIP/Folder... and go once again in the folder where you extracted lwjgl.zip and go into the doc folder and select javadoc.zip

Now you can create a new project to test your setup. The following steps have to be done at each project.

  1. Create a new Java Application project via File -> New project...
  2. In your project right-click on Libraries and select Add Library...
  3. Of course select your LWJGL3 library
  4. Now right-click your project and click on Properties
  5. Go to the Run category
  6. Click into VM Options and type -Dorg.lwjgl.librarypath="<path to the extracted lwjgl.zip>\native\<os>\<arch>" where <os> is either windows, linux or macosx and <arch> is either x86 or x64, depending on your system.

Eclipse

The following steps have to be done for each project.

  1. Create a new project via File -> New -> Java Project
  2. Right-click your project and select Properties
  3. Go into the Java Build Path category
  4. Select the Libraries tab
  5. Click on Add External Jars..., then go to your folder where you extracted lwjgl.zip and go in the jar folder and select lwjgl.jar and disruptor.jar
  6. Expand lwjgl.jar
  7. Select Source attachment and click on Edit...
  8. Click on *External File... and go to your folder where you extracted lwjgl.zip and select src.zip
  9. Select Javadoc location and click on Edit...
  10. Click on Browse... next to Archive path, go to your folder where you extracted lwjgl.zip and into the doc folder and select javadoc.zip
  11. Now in your main menu select Run -> Run Configurations...
  12. Select the Arguments tab
  13. Click into VM arguments and type -Dorg.lwjgl.librarypath="<path to the extracted lwjgl.zip>\native\<os>\<arch>" where <os> is either windows, linux or macosx and <arch> is either x86 or x64, depending on your system.

IntelliJ

The following steps have to be done for each project.

  1. Create a new Java project via File -> New Project
  2. In your main menu select File -> Project Structure
  3. Select the Modules category
  4. Select the Dependencies tab
  5. Click on the green + -> Library... -> Java and choose your LWJGL3 global library, if you haven't made that before do the following steps
    1. Click on the green + -> Library... -> Java, then go to your folder where you extracted lwjgl.zip and go in the jar folder and select lwjgl.jar and disruptor.jar
    2. Click on the green +, then go to your folder where you extracted lwjgl.zip and select src.zip
    3. Click on the green +, then go again to the folder where you extracted lwjgl.zip and go into the doc folder and select javadoc.zip
    4. Set the Level to Global Library so you can add the library in a new project faster
  6. Now in your main menu select Run -> Edit Configurations
  7. Click on the green + and select Application
  8. Click into Main class and type the path to your main class
  9. Click into VM options and type -Dorg.lwjgl.librarypath="<path to the extracted lwjgl.zip>\native\<os>\<arch>" where <os> is either windows, linux or macosx and <arch> is either x86 or x64, depending on your system.

Test your setup

After setting up your IDE just copy and paste this code, then run it. If it runs successfully then your setup is complete.
If you get Exception in thread "main" java.lang.UnsatisfiedLinkError: Failed to load the native library: lwjgl you have not set the org.lwjgl.librarypath correctly. This is the most important part when setting up your project, so make sure you have set the native path according to your system.

package test.setup;

import org.lwjgl.Sys;

public class TestSetup {

    public static void main(String[] args) {
        System.out.println("LWJGL Version " + Sys.getVersion() + " is working.");
    }
}

Getting started

With LWJGL3 comes the GLFW library which provides the creation of an OpenGL context and input features.
This very first Guide is based on the getting started guide of GLFW3.

Initializing the OpenGL context

The first thing you should do is setting the error callback, so you can see if an error occurred even if GLFW wasn't initialized yet.
It should be noted, that you need to have a strong reference to any callbacks in LWJGL. This is due to the nature of the garbage collector, if you don't have a strong reference to the callback the VM won't know that you need it and it could get garbage collected which results in a ClosureError. So make sure to have a class variable for each callback.

Now back to the error callback, to create one you can use the Callbacks class of the LWJGL which has a function named errorCallbackPrint which creates a GLFWErrorCallback for you.
Another way to make an error callback is to just create a new GLFWErrorCallback and overriding its invoke function.
For the sake of easiness we just create an error callback that prints to System.err.

private GLFWErrorCallback errorCallback = Callbacks.errorCallbackPrint(System.err);

After that we just have to set the callback.

glfwSetErrorCallback(errorCallback);

The next step is to initialize GLFW, this is done by calling glfwInit().

if (glfwInit() != GL_TRUE) {
    throw new IllegalStateException("Unable to initialize GLFW");
}

Now that GLFW is initialized we can start creating a window.
In GLFW this is done by calling glfwCreateWindow(width, height, title, monitor, share), in this guide we will ignore monitor and share for now.
You can also set some window hints, like GLFW_RESIZABLE or GLFW_VISIBLE, but at this part of the tutorial we will just go with the default window hints.
If the creation fails this method just returns NULL which is 0 in LWJGL, but you can make a static import of the MemoryUtil to just write NULL, so you don't have to bother if the value get changed sometime. But normally the method won't fail and returns a handle for the window.

long window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
if (window == NULL) {
    glfwTerminate();
    throw new RuntimeException("Failed to create the GLFW window");
}

With the window created we can set up some other callbacks for that window like a key callback.
Don't forget to make a strong reference to the callback. For creating it you have to override the invoke function of GLFWKeyCallback.
The following key callback will for example check if the escape key was pressed and will then tell the window to close.

private GLFWKeyCallback keyCallback = new GLFWKeyCallback() {
    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {
        if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
            glfwSetWindowShouldClose(window, GL_TRUE);
        }
    }
};

After creating the key callback you can register it to your window.

glfwSetKeyCallback(window, keyCallback);

When done creating a window you can also create the OpenGL context, which is needed for rendering.
This is done by calling glfwMakeContextCurrent(window). In LWJGL you also have to call createFromCurrent() from the GLContext class, so that the library can detect the context and make the OpenGL bindings available for use.

glfwMakeContextCurrent(window);
GLContext.createFromCurrent();

Now that you have your OpenGL context you can start rendering.

Update and Rendering loop

We want our application to run until the window should get closed, so just do a simple while loop.

while (glfwWindowShouldClose(window) != GL_TRUE) {
    /* Do something */
}

The GL_TRUE comes from the GL11 class and is really just a 1, but it is best if you write it out and make a static import to it.

Inside the loop you can do any OpenGL calls to render your application, in the example code it is just a rotating triangle.
For the correct rotating we need a time source. Luckily GLFW3 has its own high-resolution timer by calling glfwGetTime(). It will give you the passed seconds since glfwInit() as a double.

double time = glfwGetTime();

After doing your OpenGL calls you have to swap the color buffers, because GLFW uses double-buffering. You can do this by calling glfwSwapBuffers(window).
Another thing to do is processing events like the key events through glfwPollEvents(). You could also do glfwWaitEvents() if your application should only update when you receive new input.

glfwSwapBuffers(window);
glfwPollEvents();

For the example OpenGL calls just look into Introduction.java provided in a link below.

Ending the Application

When you are ending your application you should release your callbacks, destroy your window and terminate GLFW, so that any allocated resources get released.
First you should destroy your window, and after that release the event callbacks that were registered to that window like the key event.

glfwDestroyWindow(window);
keyCallback.release();

After destroying the window and releasing its callbacks you should terminate GLFW and finally release the error callback.

glfwTerminate();
errorCallback.release();

This is everything you should know for a quick start into LWJGL3, if something is unclear or you found a mistake just tell me.

Next Steps

In the next tutorial we will take a look into game loops, which are the core of every game.
Until then enjoy testing LWJGL3 out!

Source Code

References

Clone this wiki locally