Comprehensive ctypes-based OpenGL binding for Python providing access to OpenGL, GLU, and GLUT functionality
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Cross-platform OpenGL support providing automatic platform detection and unified interface for Windows (WGL), Linux/X11 (GLX), macOS (CGL/AGL), and embedded systems (EGL). Includes dynamic library loading, extension detection, and context management across different operating systems.
Automatic platform detection with manual override capabilities for specialized use cases.
def GetCurrentPlatform():
"""
Get currently active platform implementation.
Returns:
Platform instance (Win32Platform, GLXPlatform, DarwinPlatform, etc.)
"""
def setPlatform(key: str):
"""
Manually set platform implementation.
Parameters:
- key: Platform identifier ('nt', 'linux', 'darwin', 'glx', 'egl', 'osmesa')
Note: Must be called before importing GL.* modules as extension
procedure lookup is platform dependent.
Environment variable PYOPENGL_PLATFORM provides user control.
"""
# Automatic platform detection based on sys.platform
PLATFORM_MAPPINGS = {
'nt': 'Win32Platform', # Windows
'darwin': 'DarwinPlatform', # macOS
'linux': 'GLXPlatform', # Linux
'linux2': 'GLXPlatform', # Linux (older Python)
'posix': 'GLXPlatform', # Generic POSIX
}
# Manual platform selection
MANUAL_PLATFORMS = {
'glx': 'GLXPlatform', # X11/GLX (Linux, Unix)
'egl': 'EGLPlatform', # EGL (embedded, Wayland)
'osmesa': 'OSMesaPlatform', # Off-screen Mesa
'wayland': 'EGLPlatform', # Wayland compositor
'xwayland': 'EGLPlatform', # XWayland (X11 over Wayland)
}Windows-specific OpenGL implementation using WGL (Windows OpenGL) extensions.
class Win32Platform:
"""
Windows platform implementation using WGL extensions.
Handles OpenGL context creation and extension loading on Windows.
"""
def getGLExtensionPointer(self, name: str):
"""
Get OpenGL extension function pointer on Windows.
Parameters:
- name: Extension function name
Returns:
Function pointer or None if not available
"""
def getCurrentContext(self):
"""Get current OpenGL context handle (HGLRC)."""
def contextIsValid(self, context) -> bool:
"""Check if OpenGL context is valid."""
# Windows-specific constants and functions
# Available when platform is Win32Platform
from OpenGL.WGL import *Linux and Unix platform support using GLX (GLX) extensions for X Window System integration.
class GLXPlatform:
"""
Linux/Unix platform implementation using GLX extensions.
Handles OpenGL context creation and extension loading on X11 systems.
"""
def getGLExtensionPointer(self, name: str):
"""
Get OpenGL extension function pointer on Linux/X11.
Parameters:
- name: Extension function name
Returns:
Function pointer or None if not available
"""
def getCurrentContext(self):
"""Get current OpenGL context (GLXContext)."""
def contextIsValid(self, context) -> bool:
"""Check if GLX context is valid."""
# GLX-specific constants and functions
# Available when platform is GLXPlatform
from OpenGL.GLX import *macOS platform support using Core OpenGL (CGL) and Apple OpenGL (AGL) frameworks.
class DarwinPlatform:
"""
macOS platform implementation using CGL/AGL frameworks.
Handles OpenGL context creation and extension loading on macOS.
"""
def getGLExtensionPointer(self, name: str):
"""
Get OpenGL extension function pointer on macOS.
Parameters:
- name: Extension function name
Returns:
Function pointer or None if not available
"""
def getCurrentContext(self):
"""Get current OpenGL context (CGLContextObj)."""
def contextIsValid(self, context) -> bool:
"""Check if CGL context is valid."""
# macOS-specific constants and functions
# Available when platform is DarwinPlatform
from OpenGL.AGL import * # Legacy Apple OpenGLEGL (Embedded-System Graphics Library) support for embedded systems and Wayland compositors.
class EGLPlatform:
"""
EGL platform implementation for embedded systems and Wayland.
Provides OpenGL ES and desktop OpenGL context creation via EGL.
"""
def getGLExtensionPointer(self, name: str):
"""
Get OpenGL extension function pointer via EGL.
Parameters:
- name: Extension function name
Returns:
Function pointer or None if not available
"""
def getCurrentContext(self):
"""Get current EGL context."""
def contextIsValid(self, context) -> bool:
"""Check if EGL context is valid."""
# EGL-specific constants and functions
# Available when platform supports EGL
from OpenGL.EGL import *Mesa off-screen rendering support for headless OpenGL rendering without window system.
class OSMesaPlatform:
"""
OSMesa platform implementation for off-screen rendering.
Enables OpenGL rendering without window system or display.
"""
def getGLExtensionPointer(self, name: str):
"""
Get OpenGL extension function pointer via OSMesa.
Parameters:
- name: Extension function name
Returns:
Function pointer or None if not available
"""
def getCurrentContext(self):
"""Get current OSMesa context."""
def contextIsValid(self, context) -> bool:
"""Check if OSMesa context is valid."""
# OSMesa-specific functions
# Available when platform is OSMesaPlatform
from OpenGL.osmesa import *Cross-platform dynamic library loading with automatic library discovery.
class CtypesLoader:
"""
Cross-platform dynamic library loader using ctypes.
Handles loading OpenGL libraries with platform-specific paths.
"""
def loadLibrary(self, name: str):
"""
Load dynamic library by name.
Parameters:
- name: Library name (platform-specific)
Returns:
Loaded library handle
"""
def getFunction(self, library, name: str):
"""
Get function from loaded library.
Parameters:
- library: Library handle from loadLibrary()
- name: Function name
Returns:
Function pointer or None if not found
"""
# Platform-specific library names
LIBRARY_NAMES = {
'nt': ['opengl32.dll', 'glu32.dll', 'glut32.dll'],
'darwin': ['OpenGL.framework/OpenGL', 'GLUT.framework/GLUT'],
'linux': ['libGL.so.1', 'libGLU.so.1', 'libglut.so.3'],
'posix': ['libGL.so', 'libGLU.so', 'libglut.so']
}Platform-aware extension detection and function loading with fallback mechanisms.
def hasExtension(extension_name: str) -> bool:
"""
Check if OpenGL extension is available on current platform.
Parameters:
- extension_name: Extension name (e.g., "GL_ARB_vertex_buffer_object")
Returns:
True if extension is supported on current platform
"""
def getExtensionFunction(name: str):
"""
Get platform-specific extension function pointer.
Parameters:
- name: Extension function name
Returns:
Function pointer or None if not available
"""
class ExtensionQuerier:
"""
Platform-aware extension detection and management.
Handles differences in extension reporting across platforms.
"""
def __init__(self, platform):
"""
Parameters:
- platform: Platform implementation instance
"""
def hasExtension(self, name: str) -> bool:
"""Check if extension is available."""
def getExtensions(self) -> list:
"""Get list of all available extensions."""Platform-specific context information and capabilities query.
def getContextInfo() -> dict:
"""
Get comprehensive OpenGL context information.
Returns:
Dictionary containing:
- 'vendor': OpenGL vendor string
- 'renderer': OpenGL renderer string
- 'version': OpenGL version string
- 'extensions': List of available extensions
- 'platform': Current platform name
- 'context': Platform-specific context info
"""
def getRendererInfo() -> dict:
"""
Get detailed renderer capabilities.
Returns:
Dictionary with platform-specific renderer information
"""
def getPlatformInfo() -> dict:
"""
Get platform-specific information.
Returns:
Dictionary containing platform details and capabilities
"""import OpenGL
import os
# Set platform before importing GL modules
if os.environ.get('USE_EGL'):
OpenGL.setPlatform('egl')
elif os.environ.get('WAYLAND_DISPLAY'):
OpenGL.setPlatform('wayland')
else:
# Use automatic detection
pass
# Now import GL modules
from OpenGL.GL import *from OpenGL.platform import getContextInfo, GetCurrentPlatform
# Get platform information
platform = GetCurrentPlatform()
print(f"Platform: {platform.__class__.__name__}")
# Get context information (requires active OpenGL context)
try:
info = getContextInfo()
print(f"Vendor: {info['vendor']}")
print(f"Renderer: {info['renderer']}")
print(f"Version: {info['version']}")
print(f"Extensions: {len(info['extensions'])} available")
except:
print("No OpenGL context available")from OpenGL.platform import hasExtension, getExtensionFunction
# Check for specific extensions
extensions_to_check = [
'GL_ARB_vertex_buffer_object',
'GL_ARB_shader_objects',
'GL_EXT_framebuffer_object'
]
for ext in extensions_to_check:
if hasExtension(ext):
print(f"✓ {ext} is available")
else:
print(f"✗ {ext} is not available")
# Get extension function
vbo_gen_func = getExtensionFunction('glGenBuffersARB')
if vbo_gen_func:
print("VBO functions available")import OpenGL
# Force OSMesa for headless rendering
OpenGL.setPlatform('osmesa')
from OpenGL.GL import *
from OpenGL.osmesa import *
# Create off-screen context
width, height = 800, 600
context = OSMesaCreateContext(OSMESA_RGBA, None)
buffer = (ctypes.c_ubyte * (width * height * 4))()
if OSMesaMakeCurrent(context, buffer, GL_UNSIGNED_BYTE, width, height):
# Now have working OpenGL context for rendering
glViewport(0, 0, width, height)
glClearColor(0.2, 0.3, 0.4, 1.0)
glClear(GL_COLOR_BUFFER_BIT)
# Render scene...
# Clean up
OSMesaDestroyContext(context)from OpenGL.platform import GetCurrentPlatform
import sys
platform = GetCurrentPlatform()
if sys.platform == 'win32':
# Windows-specific features
from OpenGL.WGL import *
print("Using WGL extensions")
elif sys.platform == 'darwin':
# macOS-specific features
from OpenGL.AGL import *
print("Using CGL/AGL frameworks")
else:
# Linux/Unix-specific features
from OpenGL.GLX import *
print("Using GLX extensions")import os
# User can control platform selection
platform_override = os.environ.get('PYOPENGL_PLATFORM')
if platform_override:
print(f"Using platform override: {platform_override}")
# Other environment variables
if os.environ.get('PYOPENGL_USE_ACCELERATE') == '0':
print("Acceleration disabled by environment")
if os.environ.get('PYOPENGL_ERROR_CHECKING') == '0':
print("Error checking disabled by environment")# Windows
OPENGL32_DLL: str = "opengl32.dll"
GLU32_DLL: str = "glu32.dll"
GLUT32_DLL: str = "glut32.dll"
# macOS
OPENGL_FRAMEWORK: str = "OpenGL.framework/OpenGL"
GLUT_FRAMEWORK: str = "GLUT.framework/GLUT"
# Linux/Unix
LIBGL_SO: str = "libGL.so.1"
LIBGLU_SO: str = "libGLU.so.1"
LIBGLUT_SO: str = "libglut.so.3"PLATFORM_NT: str = "nt" # Windows
PLATFORM_DARWIN: str = "darwin" # macOS
PLATFORM_LINUX: str = "linux" # Linux
PLATFORM_GLX: str = "glx" # X11/GLX
PLATFORM_EGL: str = "egl" # EGL
PLATFORM_OSMESA: str = "osmesa" # Off-screen Mesa
PLATFORM_WAYLAND: str = "wayland" # WaylandWGL_EXTENSIONS: list # Windows WGL extensions
GLX_EXTENSIONS: list # Linux GLX extensions
CGL_EXTENSIONS: list # macOS CGL extensions
EGL_EXTENSIONS: list # EGL extensionsInstall with Tessl CLI
npx tessl i tessl/pypi-pyopengl