base.window.WindowConfig

moderngl_window.context.base.window.WindowConfig[source]

Creating a WindowConfig instance is the simplest interface this library provides to open and window, handle inputs and provide simple shortcut method for loading basic resources. It’s appropriate for projects with basic needs.

Example:

import moderngl_window

class MyConfig(moderngl_window.WindowConfig):
    gl_version = (3, 3)
    window_size = (1920, 1080)
    aspect_ratio = 16 / 9
    title = "My Config"
    resizable = False
    samples = 8

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # Do other initialization here

    def render(self, time: float, frametime: float):
        # Render stuff here with ModernGL

    def resize(self, width: int, height: int):
        print("Window was resized. buffer size is {} x {}".format(width, height))

    def mouse_position_event(self, x, y, dx, dy):
        print("Mouse position:", x, y)

    def mouse_press_event(self, x, y, button):
        print("Mouse button {} pressed at {}, {}".format(button, x, y))

    def mouse_release_event(self, x: int, y: int, button: int):
        print("Mouse button {} released at {}, {}".format(button, x, y))

    def key_event(self, key, action, modifiers):
        print(key, action, modifiers)

Methods

WindowConfig.__init__(ctx: Context = None, wnd: BaseWindow = None, timer: BaseTimer = None, **kwargs)[source]

Initialize the window config

Keyword Arguments:
  • ctx (moderngl.Context) – The moderngl context

  • wnd – The window instance

  • timer – The timer instance

classmethod WindowConfig.run()[source]

Shortcut for running a WindowConfig.

This executes the following code:

import moderngl_window
moderngl_window.run_window_config(cls)
WindowConfig.render(time: float, frame_time: float)[source]

Renders the assigned effect

Parameters:
  • time (float) – Current time in seconds

  • frame_time (float) – Delta time from last frame in seconds

WindowConfig.resize(width: int, height: int)[source]

Called every time the window is resized in case the we need to do internal adjustments.

Parameters:
  • width (int) – width in buffer size (not window size)

  • height (int) – height in buffer size (not window size)

WindowConfig.close()[source]

Called when the window is closed

classmethod WindowConfig.add_arguments(parser: ArgumentParser)[source]

Add arguments to default argument parser. Add arguments using add_argument(..).

Parameters:

parser (ArgumentParser) – The default argument parser.

WindowConfig.key_event(key: Any, action: Any, modifiers: KeyModifiers)[source]

Called for every key press and release. Depending on the library used, key events may trigger repeating events during the pressed duration based on the configured key repeat on the users operating system.

Parameters:
  • key – The key that was press. Compare with self.wnd.keys.

  • action – self.wnd.keys.ACTION_PRESS or ACTION_RELEASE

  • modifiers – Modifier state for shift, ctrl and alt

WindowConfig.mouse_position_event(x: int, y: int, dx: int, dy: int)[source]

Reports the current mouse cursor position in the window

Parameters:
  • x (int) – X postion of the mouse cursor

  • y (int) – Y position of the mouse cursor

  • dx (int) – X delta postion

  • dy (int) – Y delta position

WindowConfig.mouse_press_event(x: int, y: int, button: int)[source]

Called when a mouse button in pressed

Parameters:
  • x (int) – X position the press ocurred

  • y (int) – Y position the press ocurred

  • button (int) – 1 = Left button, 2 = right button

WindowConfig.mouse_release_event(x: int, y: int, button: int)[source]

Called when a mouse button in released

Parameters:
  • x (int) – X position the release ocurred

  • y (int) – Y position the release ocurred

  • button (int) – 1 = Left button, 2 = right button

WindowConfig.mouse_drag_event(x: int, y: int, dx: int, dy: int)[source]

Called when the mouse is moved while a button is pressed.

Parameters:
  • x (int) – X postion of the mouse cursor

  • y (int) – Y position of the mouse cursor

  • dx (int) – X delta postion

  • dy (int) – Y delta position

WindowConfig.mouse_scroll_event(x_offset: float, y_offset: float)[source]

Called when the mouse wheel is scrolled.

Some input devices also support horizontal scrolling, but vertical scrolling is fairly universal.

Parameters:
  • x_offset (int) – X scroll offset

  • y_offset (int) – Y scroll offset

WindowConfig.unicode_char_entered(char: str)[source]

Called when the user entered a unicode character.

Parameters:

char (str) – The character entered

WindowConfig.load_texture_2d(path: str, flip=True, flip_x=False, flip_y=True, mipmap=False, mipmap_levels: Tuple[int, int] | None = None, anisotropy=1.0, **kwargs) Texture[source]

Loads a 2D texture.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Parameters:

path (str) – Path to the texture relative to search directories

Keyword Arguments:
  • flip (boolean) – (Use `flip_y) Flip the image vertically (top to bottom)

  • flip_x (boolean) – Flip the image horizontally (left to right)

  • flip_y (boolean) – Flip the image vertically (top to bottom)

  • mipmap (bool) – Generate mipmaps. Will generate max possible levels unless mipmap_levels is defined.

  • mipmap_levels (tuple) – (base, max_level) controlling mipmap generation. When defined the mipmap parameter is automatically True

  • anisotropy (float) – Number of samples for anisotropic filtering

  • **kwargs – Additional parameters to TextureDescription

Returns:

Texture instance

Return type:

moderngl.Texture

WindowConfig.load_texture_array(path: str, layers: int = 0, flip=True, mipmap=False, mipmap_levels: Tuple[int, int] | None = None, anisotropy=1.0, **kwargs) TextureArray[source]

Loads a texture array.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Parameters:

path (str) – Path to the texture relative to search directories

Keyword Arguments:
  • layers (int) – How many layers to split the texture into vertically

  • flip (boolean) – Flip the image horizontally

  • mipmap (bool) – Generate mipmaps. Will generate max possible levels unless mipmap_levels is defined.

  • mipmap_levels (tuple) – (base, max_level) controlling mipmap generation. When defined the mipmap parameter is automatically True

  • anisotropy (float) – Number of samples for anisotropic filtering

  • **kwargs – Additional parameters to TextureDescription

Returns:

The texture instance

Return type:

moderngl.TextureArray

WindowConfig.load_texture_cube(pos_x: str = '', pos_y: str = '', pos_z: str = '', neg_x: str = '', neg_y: str = '', neg_z: str = '', flip=False, flip_x=False, flip_y=False, mipmap=False, mipmap_levels: Tuple[int, int] | None = None, anisotropy=1.0, **kwargs) TextureCube[source]

Loads a texture cube.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Keyword Arguments:
  • pos_x (str) – Path to texture representing positive x face

  • pos_y (str) – Path to texture representing positive y face

  • pos_z (str) – Path to texture representing positive z face

  • neg_x (str) – Path to texture representing negative x face

  • neg_y (str) – Path to texture representing negative y face

  • neg_z (str) – Path to texture representing negative z face

  • flip (boolean) – (Use flip_y)Flip the image vertically (top to bottom)

  • flip_x (boolean) – Flip the image horizontally (left to right)

  • flip_y (boolean) – Flip the image vertically (top to bottom)

  • mipmap (bool) – Generate mipmaps. Will generate max possible levels unless mipmap_levels is defined.

  • mipmap_levels (tuple) – (base, max_level) controlling mipmap generation. When defined the mipmap parameter is automatically True

  • anisotropy (float) – Number of samples for anisotropic filtering

  • **kwargs – Additional parameters to TextureDescription

Returns:

Texture instance

Return type:

moderngl.TextureCube

WindowConfig.load_program(path=None, vertex_shader=None, geometry_shader=None, fragment_shader=None, tess_control_shader=None, tess_evaluation_shader=None, defines: dict | None = None, varyings: List[str] | None = None) Program[source]

Loads a shader program.

Note that path should only be used if all shaders are defined in the same glsl file separated by defines.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Keyword Arguments:
  • path (str) – Path to a single glsl file

  • vertex_shader (str) – Path to vertex shader

  • geometry_shader (str) – Path to geometry shader

  • fragment_shader (str) – Path to fragment shader

  • tess_control_shader (str) – Path to tessellation control shader

  • tess_evaluation_shader (str) – Path to tessellation eval shader

  • defines (dict) – #define values to replace in the shader source. Example: {'VALUE1': 10, 'VALUE2': '3.1415'}.

  • varyings (List[str]) – Out attribute names for transform shaders

Returns:

The program instance

Return type:

moderngl.Program

WindowConfig.load_compute_shader(path, defines: Dict | None = None, **kwargs) ComputeShader[source]

Loads a compute shader.

Parameters:
  • path (str) – Path to a single glsl file

  • defines (dict) – #define values to replace in the shader source. Example: {'VALUE1': 10, 'VALUE2': '3.1415'}.

Returns:

The compute shader

Return type:

moderngl.ComputeShader

WindowConfig.load_text(path: str, **kwargs) str[source]

Load a text file.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Parameters:
  • path (str) – Path to the file relative to search directories

  • **kwargs – Additional parameters to DataDescription

Returns:

Contents of the text file

Return type:

str

WindowConfig.load_json(path: str, **kwargs) dict[source]

Load a json file

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Parameters:
  • path (str) – Path to the file relative to search directories

  • **kwargs – Additional parameters to DataDescription

Returns:

Contents of the json file

Return type:

dict

WindowConfig.load_binary(path: str, **kwargs) bytes[source]

Load a file in binary mode.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Parameters:
  • path (str) – Path to the file relative to search directories

  • **kwargs – Additional parameters to DataDescription

Returns:

The byte data of the file

Return type:

bytes

WindowConfig.load_scene(path: str, cache=False, attr_names=<class 'moderngl_window.geometry.attributes.AttributeNames'>, kind=None, **kwargs) Scene[source]

Loads a scene.

If the path is relative the resource system is used expecting one or more resource directories to be registered first. Absolute paths will attempt to load the file directly.

Keyword Arguments:
  • path (str) – Path to the file relative to search directories

  • cache (str) – Use the loader caching system if present

  • attr_names (AttributeNames) – Attrib name config

  • kind (str) – Override loader kind

  • **kwargs – Additional parameters to SceneDescription

Returns:

The scene instance

Return type:

Scene

Attributes

WindowConfig.window_size

Size of the window.

# Default value
window_size = (1280, 720)
WindowConfig.vsync

Enable or disable vsync.

# Default value
vsync = True
WindowConfig.fullscreen

Open the window in fullscreen mode.

# Default value
fullscreen = False
WindowConfig.resizable

Determines of the window should be resizable

# Default value
resizable = True
WindowConfig.gl_version

The minimum required OpenGL version required

# Default value
gl_version = (3, 3)
WindowConfig.title

Title of the window

# Default value
title = "Example"
WindowConfig.aspect_ratio

The enforced aspect ratio of the viewport. When specified back borders will be calculated both vertically and horizontally if needed.

This property can be set to None to disable the fixed viewport system.

# Default value
aspect_ratio = 16 / 9
WindowConfig.cursor

Determines if the mouse cursor should be visible inside the window. If enabled on some platforms

# Default value
cursor = True
WindowConfig.clear_color

The color the active framebuffer is cleared with. This attribute is expected to be in the form of (r, g, b, a) in the range [0.0, 1.0]

If the value is None the screen will not be cleared every frame.

# Default value
clear_color = (0.0, 0.0, 0.0, 0.0)
# Disable screen clearing
clear_color = None
WindowConfig.samples

Number of samples to use in multisampling.

# Default value
samples = 4
WindowConfig.resource_dir

Absolute path to your resource directory containing textures, scenes, shaders/programs or data files. The load_ methods in this class will look for resources in this path. This attribute can be a str or a pathlib.Path.

# Default value
resource_dir = None
WindowConfig.log_level

Sets the log level for this library using the standard logging module.

# Default value
log_level = logging.INFO
WindowConfig.argv

The parsed command line arguments.