lwjgl3
LWJGL is a Java library that enables cross-platform access to popular native APIs useful in the development of graphics (OpenGL, Vulkan, bgfx), audio (OpenAL, Opus), parallel computing (OpenCL, CUDA) and XR (OpenVR, LibOVR, OpenXR) applications.
Top Related Projects
A multi-platform library for OpenGL, OpenGL ES, Vulkan, window and input
Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
A simple and easy-to-use library to enjoy videogames programming
Simple Directmedia Layer
Hazel Engine
FNA - Accuracy-focused XNA4 reimplementation for open platforms
Quick Overview
LWJGL (Lightweight Java Game Library) 3 is a Java library that enables cross-platform access to popular native APIs useful in the development of graphics (OpenGL, Vulkan), audio (OpenAL), parallel computing (OpenCL), and XR (OpenXR) applications. It provides low-level bindings to native libraries commonly used in game development and multimedia applications.
Pros
- Cross-platform compatibility (Windows, macOS, Linux)
- High performance due to direct access to native APIs
- Extensive documentation and community support
- Regular updates and active development
Cons
- Steep learning curve for beginners
- Requires understanding of low-level graphics programming concepts
- Limited high-level abstractions compared to some game engines
- Potential compatibility issues with certain hardware configurations
Code Examples
- Creating a GLFW window:
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
public class HelloWorld {
public static void main(String[] args) {
// Initialize GLFW
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW");
// Create the window
long window = glfwCreateWindow(300, 300, "Hello World!", 0, 0);
if (window == 0)
throw new RuntimeException("Failed to create the GLFW window");
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable v-sync
glfwSwapInterval(1);
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
GL.createCapabilities();
// Set the clear color
glClearColor(1.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)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
glfwSwapBuffers(window); // swap the color buffers
glfwPollEvents();
}
}
}
- Loading and playing a sound using OpenAL:
import org.lwjgl.openal.*;
import org.lwjgl.system.*;
import java.nio.*;
import static org.lwjgl.openal.AL10.*;
import static org.lwjgl.system.MemoryStack.*;
public class SoundExample {
public static void main(String[] args) {
// Initialize OpenAL
ALCCapabilities alcCapabilities = ALC.createCapabilities(alcOpenDevice(alcGetString(0, ALC_DEFAULT_DEVICE_SPECIFIER)));
ALCapabilities alCapabilities = AL.createCapabilities(alcCapabilities);
// Load sound file (assuming you have a method to load WAV data)
ByteBuffer soundData = loadWAVData("sound.wav");
// Create buffer and source
int buffer = alGenBuffers();
alBufferData(buffer, AL_FORMAT_STEREO16, soundData, 44100);
int source = alGenSources();
alSourcei(source, AL_BUFFER, buffer);
// Play the sound
alSourcePlay(source);
// Wait for the sound to finish
while (alGetSourcei(source, AL_SOURCE_STATE) == AL_PLAYING) {
// Do nothing
}
// Clean up
alDeleteSources(source);
alDeleteBuffers(buffer);
alcDestroyContext(alcGetCurrentContext());
alcCloseDevice(alcGetContextsDevice(alcGetCurrentContext()));
}
}
Getting Started
1
Competitor Comparisons
A multi-platform library for OpenGL, OpenGL ES, Vulkan, window and input
Pros of GLFW
- Lightweight and focused solely on window creation and input handling
- Easier to integrate into existing C/C++ projects
- More straightforward API with less abstraction
Cons of GLFW
- Limited to OpenGL and Vulkan, while LWJGL3 supports more APIs
- Lacks additional features like audio support that LWJGL3 provides
- Requires manual binding for languages other than C/C++
Code Comparison
GLFW (C):
#include <GLFW/glfw3.h>
int main() {
glfwInit();
GLFWwindow* window = glfwCreateWindow(640, 480, "GLFW Window", NULL, NULL);
while (!glfwWindowShouldClose(window)) {
glfwSwapBuffers(window);
}
}
LWJGL3 (Java):
import org.lwjgl.glfw.GLFW;
public class Main {
public static void main(String[] args) {
GLFW.glfwInit();
long window = GLFW.glfwCreateWindow(640, 480, "LWJGL3 Window", 0, 0);
while (!GLFW.glfwWindowShouldClose(window)) {
GLFW.glfwSwapBuffers(window);
}
}
}
Both libraries provide similar functionality for window creation and management, but LWJGL3 wraps GLFW (among other libraries) in a Java-friendly interface, while GLFW is a standalone C library focused on core windowing and input functionality.
Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
Pros of ImGui
- Lightweight and easy to integrate into existing projects
- Immediate mode GUI, allowing for rapid prototyping and development
- Cross-platform compatibility with minimal dependencies
Cons of ImGui
- Limited to 2D user interfaces, lacking 3D rendering capabilities
- Requires more manual management of UI state compared to retained mode GUIs
- Less extensive ecosystem and tooling support
Code Comparison
ImGui (C++):
ImGui::Begin("Hello, world!");
ImGui::Text("This is some useful text.");
if (ImGui::Button("Save"))
MySaveFunction();
ImGui::End();
LWJGL3 (Java):
try (MemoryStack stack = stackPush()) {
IntBuffer pWidth = stack.mallocInt(1);
IntBuffer pHeight = stack.mallocInt(1);
glfwGetWindowSize(window, pWidth, pHeight);
glViewport(0, 0, pWidth.get(0), pHeight.get(0));
}
Summary
ImGui is a lightweight, immediate mode GUI library focused on simplicity and rapid development, while LWJGL3 is a comprehensive Java library for OpenGL, OpenAL, and OpenCL development. ImGui excels in quick prototyping and simple 2D interfaces, whereas LWJGL3 offers more extensive 3D rendering capabilities and a broader range of low-level graphics and audio functionalities.
A simple and easy-to-use library to enjoy videogames programming
Pros of raylib
- Simpler API and easier to learn for beginners
- Cross-platform support with a single codebase
- Extensive documentation and examples
Cons of raylib
- Less flexible and customizable than LWJGL
- Limited to C programming language (though bindings exist for other languages)
- Smaller community and ecosystem compared to LWJGL
Code Comparison
raylib example:
#include "raylib.h"
int main(void)
{
InitWindow(800, 450, "raylib [core] example - basic window");
while (!WindowShouldClose())
{
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY);
EndDrawing();
}
CloseWindow();
return 0;
}
LWJGL example:
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
public class HelloWorld {
public static void main(String[] args) {
GLFWErrorCallback.createPrint(System.err).set();
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW");
// ... (window creation and rendering code)
}
}
The raylib example demonstrates its simplicity, while the LWJGL example shows more verbose setup but offers greater flexibility.
Simple Directmedia Layer
Pros of SDL
- Cross-platform support for multiple operating systems and architectures
- Extensive multimedia capabilities, including audio, input, and graphics
- Large and active community with extensive documentation and resources
Cons of SDL
- C-based API, which may be less intuitive for Java developers
- Requires manual memory management and pointer handling
- Limited built-in support for modern graphics APIs like Vulkan
Code Comparison
SDL (C):
SDL_Window* window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
LWJGL (Java):
long window = glfwCreateWindow(800, 600, "LWJGL Window", NULL, NULL);
glfwMakeContextCurrent(window);
GL.createCapabilities();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glfwSwapBuffers(window);
LWJGL provides a more Java-centric approach with object-oriented design and automatic memory management. It offers direct bindings to OpenGL, Vulkan, and other low-level APIs, making it well-suited for Java developers working on high-performance graphics applications. However, SDL's broader multimedia support and extensive cross-platform compatibility make it a versatile choice for general-purpose game development and multimedia applications across various programming languages.
Hazel Engine
Pros of Hazel
- Higher-level game engine framework, providing more built-in functionality
- Designed specifically for game development, with a focus on ease of use
- Includes a visual editor for scene management and asset manipulation
Cons of Hazel
- Less flexible and customizable compared to LWJGL's low-level approach
- Smaller community and ecosystem, potentially leading to fewer resources and third-party integrations
- May have a steeper learning curve for developers who prefer working closer to the hardware
Code Comparison
Hazel (C++):
class ExampleLayer : public Hazel::Layer {
public:
void OnUpdate() override {
Hazel::Renderer2D::BeginScene(m_Camera);
Hazel::Renderer2D::DrawQuad({0.0f, 0.0f}, {1.0f, 1.0f}, {1.0f, 0.0f, 0.0f, 1.0f});
Hazel::Renderer2D::EndScene();
}
};
LWJGL (Java):
public class Example {
public void render() {
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2f(0.0f, 0.0f);
glVertex2f(1.0f, 0.0f);
glVertex2f(1.0f, 1.0f);
glVertex2f(0.0f, 1.0f);
glEnd();
}
}
FNA - Accuracy-focused XNA4 reimplementation for open platforms
Pros of FNA
- Designed specifically for game development, with a focus on XNA compatibility
- Simpler API, making it easier for beginners to get started
- Cross-platform support with a consistent API across different operating systems
Cons of FNA
- More limited in scope compared to LWJGL's broader functionality
- Smaller community and ecosystem compared to LWJGL
- Less frequent updates and potentially slower adoption of new technologies
Code Comparison
FNA (C#):
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(texture, position, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
LWJGL (Java):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glBindVertexArray(0);
FNA provides a higher-level API for game development, while LWJGL offers more low-level control over graphics operations. FNA's code is more concise and game-oriented, whereas LWJGL requires more explicit OpenGL calls.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
LWJGL - Lightweight Java Game Library 3
LWJGL (https://www.lwjgl.org) is a Java library that enables cross-platform access to popular native APIs useful in the development of graphics (OpenGL/Vulkan), audio (OpenAL) and parallel computing (OpenCL) applications. This access is direct and high-performance, yet also wrapped in a type-safe and user-friendly layer, appropriate for the Java ecosystem.
LWJGL is an enabling technology and provides low-level access. It is not a framework and does not provide higher-level utilities than what the native libraries expose. As such, novice programmers are encouraged to try one of the frameworks or game engines that make use of LWJGL, before working directly with the library.
LWJGL is open source software and freely available at no charge.
Useful links:
Contact:
If you'd like to contribute, see doc/README for a quick overview of the project structure, installation instructions and configuration options.
Getting Started
As of version 3.1.0
, LWJGL is distributed as a set of modules. Only the
core module is required and all bindings are optional (but some bindings
depend on other bindings). The easiest way to download LWJGL is to use the
build configurator on the website.
The build configurator generates Maven & Gradle declarations that can be added to existing projects. This is the easiest way to use LWJGL while developing.
LWJGL can also be downloaded as a simple set of JAR files. Each module consists of the following files:
- lwjgl-<module>.jar
- lwjgl-<module>-sources.jar
- lwjgl-<module>-javadoc.jar
- lwjgl-<module>-natives-<platform>.jar (for some bindings)
To compile and run an LWJGL application, the base and natives JAR files of
the core module and each binding used should be added to the classpath. LWJGL
extracts the natives to a temporary folder and loads them automatically, so
no further configuration is necessary. If more customization is required
(e.g. when creating a platform-specific installer) the natives may be
extracted manually and loaded via java.library.path
. See the Configuration
class for more options.
LWJGL 3 requires Java 8 or later to build and run and currently supports the following platforms/architectures:
- FreeBSD x64
- Linux x64
- Linux arm64 (ARMv8/AArch64)
- Linux arm32 (ARMv7/armhf)
- Linux ppc64le
- Linux riscv64
- macOS x64
- macOS arm64
- Windows x64
- Windows x86
- Windows arm64
Example code:
- Samples (simple samples covering basic usage of LWJGL bindings)
- Demo suite (includes advanced OpenGL and Vulkan demos)
- Wiki tutorials
For migrating LWJGL 2 code to LWJGL 3, see the Migration Guide.
Troubleshooting
Most common issues faced by LWJGL users are trivially addressed with the following:
- Installation guide (lwjgl3-wiki)
- Troubleshooting guide (lwjgl3-wiki)
- Memory FAQ (lwjgl3-wiki)
LWJGLX/debug is a Java Agent that will automatically detect a lot of these issues. It can also generate a trace log that's useful when reporting issues to LWJGL.
When asking for help or when you suspect a bug in LWJGL, preparing an MVCE (Minimal, Complete, and Verifiable example) that reproduces the issue will improve the chances of a quick and useful response.
List of Supported Bindings
Khronos APIs
Library | Description |
---|---|
EGL | An interface between Khronos rendering APIs such as OpenGL ES or OpenVG and the underlying native platform window system. |
KTX (Khronos Texture) | A lightweight container for textures for OpenGL®, Vulkan® and other GPU APIs. |
OpenCL | An open, royalty-free standard for cross-platform, parallel programming of diverse processors found in personal computers, servers, mobile devices and embedded platforms. |
OpenGL | The most widely adopted 2D and 3D graphics API in the industry, bringing thousands of applications to a wide variety of computer platforms. |
OpenGL ES | A royalty-free, cross-platform API for full-function 2D and 3D graphics on embedded systems - including consoles, phones, appliances and vehicles. |
OpenXR | A royalty-free, open standard that provides high-performance access to Augmented Reality (AR) and Virtual Reality (VR)âcollectively known as XRâplatforms and devices. |
Vulkan | A new generation graphics and compute API that provides high-efficiency, cross-platform access to modern GPUs used in a wide variety of devices from PCs and consoles to mobile phones and embedded platforms. |
Display and Input
Library | Description |
---|---|
GLFW | Create multiple windows, handle user input (keyboard, mouse, gaming peripherals) and manage contexts. Also features multi-monitor support, clipboard access, file drag-n-drop, and much more. |
JAWT | The AWT native interface. |
Native File Dialog Extended | A small C library that portably invokes native file open, folder select and file save dialogs. |
tinyfd | A native dialog library. |
Audio
Library | Description |
---|---|
FMOD | An end-to-end solution for adding sound and music to any game. |
OpenAL | A cross-platform 3D audio API appropriate for use with gaming applications and many other types of audio applications. |
OpenAL Soft | An LGPL-licensed, cross-platform, software implementation of the OpenAL 3D audio API. |
Opus | A totally open, royalty-free, highly versatile audio codec. |
Graphics
Library | Description |
---|---|
Assimp | A portable Open Source library to import various well-known 3D model formats in a uniform manner. |
bgfx | Cross-platform, graphics API agnostic, âBring Your Own Engine/Frameworkâ style rendering library, licensed under permissive BSD-2 clause open source license. |
FreeType | A freely available software library to render fonts. |
HarfBuzz | A text shaping library that allows programs to convert a sequence of Unicode input into properly formatted and positioned glyph output â for any writing system and language. |
meshoptimizer | A mesh optimization library that makes meshes smaller and faster to render. |
msdfgen | A multi-channel signed distance field generator. |
NanoSVG | A simple stupid SVG parser. |
NanoVG | A small antialiased vector graphics rendering library for OpenGL. |
Nuklear | A minimal state immediate mode graphical user interface toolkit written in ANSI C and licensed under public domain. |
par_octasphere | Generates triangle meshes for spheres, rounded boxes, and capsules. |
par_shapes | Generate parametric surfaces and other simple shapes. |
par_streamlines | Triangulate wide lines and curves. |
Shaderc | A collection of libraries for shader compilation. |
SPIRV-Cross | A library for performing reflection on SPIR-V and disassembling SPIR-V back to high level languages. |
Tiny OpenEXR | A small, single header-only library to load and save OpenEXR(.exr) images. |
Tootle (AMD) | A 3D triangle mesh optimization library that improves on existing mesh preprocessing techniques. |
Vulkan Memory Allocator | An easy to integrate Vulkan memory allocation library. |
Yoga | An open-source, cross-platform layout library that implements Flexbox. |
AR/VR
Library | Description |
---|---|
LibOVR | The API of the Oculus SDK. |
OpenVR | An API and runtime that allows access to VR hardware from multiple vendors without requiring that applications have specific knowledge of the hardware they are targeting. |
stb - single-file public domain libraries for C/C++
Library | Description |
---|---|
stb_easy_font | Quick-and-dirty easy-to-deploy bitmap font for printing frame rate, etc. |
stb_image | Image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC |
stb_image_resize | Resize images larger/smaller with good quality. |
stb_image_write | Image writing to disk: PNG, TGA, BMP |
stb_perlin | Revised Perlin noise (3D input, 1D output). |
stb_rect_pack | Simple 2D rectangle packer with decent quality. |
stb_truetype | Parse, decode, and rasterize characters from truetype fonts. |
stb_vorbis | Decode ogg vorbis files from file/memory to float/16-bit signed output. |
Other
Library | Description |
---|---|
CUDA | A parallel computing platform and programming model developed by NVIDIA for general computing on GPUs. |
hwloc | A portable abstraction of the hierarchical topology of modern architectures, including NUMA memory nodes, sockets, shared caches, cores and simultaneous multithreading. |
jemalloc | A general purpose malloc implementation that emphasizes fragmentation avoidance and scalable concurrency support. |
libffi | A portable, high level programming interface to various calling conventions. |
libdivide | A library that replaces expensive integer divides with comparatively cheap multiplication and bitshifts. |
LLVM | A collection of modular and reusable compiler and toolchain technologies. |
LMDB | An extraordinarily fast, memory-efficient database. With memory-mapped files, it has the read performance of a pure in-memory database while retaining the persistence of standard disk-based databases. |
LZ4 | A lossless data compression algorithm that is focused on compression and decompression speed. |
Meow hash | An extremely fast non-cryptographic hash. |
ODBC | A C programming language interface that makes it possible for applications to access data from a variety of database management systems (DBMSs). |
Remotery | A realtime CPU/GPU profiler hosted in a single C file with a viewer that runs in a web browser. |
rpmalloc | A public domain cross platform lock free thread caching 16-byte aligned memory allocator implemented in C. |
xxHash | An Extremely fast Hash algorithm, running at RAM speed limits. |
Zstandard (zstd) | A fast lossless compression algorithm, targeting real-time compression scenarios at zlib-level and better compression ratios. |
Use of a binding is subject to the terms of the corresponding license.
Supporting this project
LWJGL exists thanks to all the people who contribute and donate to our collective.
Top Related Projects
A multi-platform library for OpenGL, OpenGL ES, Vulkan, window and input
Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
A simple and easy-to-use library to enjoy videogames programming
Simple Directmedia Layer
Hazel Engine
FNA - Accuracy-focused XNA4 reimplementation for open platforms
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot