ModernGL
ModernGL is a high-performance Python wrapper over OpenGL Core, simplifying the creation of graphics applications like scientific simulations, games, or user interfaces. It aims to provide a more Pythonic and less boilerplate-heavy API compared to direct OpenGL bindings like PyOpenGL. The current stable version is 5.12.0, with releases occurring periodically, often including breaking changes.
Warnings
- breaking Python 3.7 support was removed in ModernGL 5.9.0. Ensure your environment uses Python 3.8 or newer.
- breaking Global constants (e.g., `moderngl.BLEND`, `moderngl.DEPTH_TEST`, `moderngl.CULL_FACE`) were moved to the `Context` object in version 5.9.0. Direct access to these from the `moderngl` module will raise an `AttributeError`.
- gotcha ModernGL context creation (`moderngl.create_context()`) requires an existing OpenGL context (e.g., from a windowing library) or the `standalone=True` flag for headless rendering. Incorrect setup is a common source of errors.
- gotcha Shader compilation errors, especially with compute shaders, can sometimes lead to silent crashes without clear Python exceptions. This can be due to insufficient OpenGL version support or driver issues.
- gotcha OpenGL resources (buffers, textures, programs) should be created once during initialization and reused. Creating them repeatedly (e.g., in a rendering loop) leads to severe performance degradation and memory leaks.
- gotcha When rendering transparent objects with depth testing and blending enabled, objects must be drawn in a specific order (typically back-to-front relative to the camera) to ensure correct blending results. Incorrect order leads to visual artifacts.
Install
-
pip install moderngl
Imports
- moderngl
import moderngl
- create_context
from moderngl import create_context
- get_context
from moderngl import get_context
- BLEND
ctx.BLEND
Quickstart
import moderngl # Create a headless context or attach to an existing one # For a windowed application, ctx = moderngl.create_context() # after a window is created by a library like Pygame, GLFW, etc. ctx = moderngl.create_context(standalone=True) # Create a buffer on the GPU buf = ctx.buffer(b"Hello ModernGL World!") # Read data back from the buffer print(buf.read()) # Release resources (important for standalone contexts) # For windowed contexts, resource management is often handled by the windowing library. ctx.release()