02. Uniforms and AttributesΒΆ

02_uniforms_and_attributes

Uniforms and Attributes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import struct

import GLWindow
import ModernGL

# Window & Context

wnd = GLWindow.create_window()
ctx = ModernGL.create_context()

# Shaders & Program

prog = ctx.program([
	ctx.vertex_shader('''
		#version 330

		in vec2 vert;

		in vec3 vert_color;
		out vec3 frag_color;

		uniform vec2 scale;
		uniform float rotation;

		void main() {
			frag_color = vert_color;
			mat2 rot = mat2(
				cos(rotation), sin(rotation),
				-sin(rotation), cos(rotation)
			);
			gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
		}
	'''),
	ctx.fragment_shader('''
		#version 330

		in vec3 frag_color;
		out vec4 color;

		void main() {
			color = vec4(frag_color, 1.0);
		}
	'''),
])

# Uniforms

scale = prog.uniforms['scale']
rotation = prog.uniforms['rotation']

width, height = wnd.size
scale.value = (height / width * 0.75, 0.75)

# Buffer

vbo = ctx.buffer(struct.pack('15f',
	1.0, 0.0,
	1.0, 0.0, 0.0,

	-0.5, 0.86,
	0.0, 1.0, 0.0,

	-0.5, -0.86,
	0.0, 0.0, 1.0,
))

# Put everything together

vao = ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color'])

# Main loop

while wnd.update():
	ctx.viewport = wnd.viewport
	ctx.clear(240, 240, 240)
	rotation.value = wnd.time
	vao.render()