Rendering to a window#
By default, ModernGL does not have a window, but the moderngl-window module allows you to use one. The installation is as follows:
pip install moderngl-window
moderngl-window uses pyglet as its default backend. It is installed automatically along with moderngl-window. However, its use is limited to the supported functionality in moderngl_window.WindowConfig
.
Entire source
1import moderngl_window as glw
2import numpy as np
3
4window_cls = glw.get_local_window_cls('pyglet')
5window = window_cls(
6 size=(512, 512), fullscreen=False, title='ModernGL Window',
7 resizable=False, vsync=True, gl_version=(3, 3)
8)
9ctx = window.ctx
10glw.activate_context(window, ctx=ctx)
11window.clear()
12window.swap_buffers()
13
14prog = ctx.program(
15 vertex_shader="""
16 #version 330
17
18 in vec2 in_vert;
19 in vec3 in_color;
20
21 out vec3 v_color;
22
23 void main() {
24 v_color = in_color;
25 gl_Position = vec4(in_vert, 0.0, 1.0);
26 }
27 """,
28 fragment_shader="""
29 #version 330
30
31 in vec3 v_color;
32
33 out vec3 f_color;
34
35 void main() {
36 f_color = v_color;
37 }
38 """,
39)
40
41x = np.linspace(-1.0, 1.0, 50)
42y = np.random.rand(50) - 0.5
43r = np.zeros(50)
44g = np.ones(50)
45b = np.zeros(50)
46
47vertices = np.dstack([x, y, r, g, b])
48
49vbo = ctx.buffer(vertices.astype("f4").tobytes())
50vao = ctx.vertex_array(prog, vbo, "in_vert", "in_color")
51
52fbo = ctx.framebuffer(
53 color_attachments=[ctx.texture((512, 512), 3)]
54)
55
56
57while not window.is_closing:
58 fbo.use()
59 fbo.clear(0.0, 0.0, 0.0, 1.0)
60 vao.render(gl.LINE_STRIP)
61
62 ctx.copy_framebuffer(window.fbo, fbo)
63
64 window.swap_buffers()
You can read the full usage of moderngl-window in its documentation.