/
test.py
159 lines (122 loc) · 4.42 KB
/
test.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import glfw
import numpy as np
from pyrr import Matrix44
from OpenGL.GL import glGenVertexArrays, glDeleteBuffers, glBufferData, \
GL_ARRAY_BUFFER, glBindVertexArray, glBindBuffer, glGenBuffers, GL_FLOAT, \
GL_FALSE, glVertexAttribPointer, shaders, GL_STATIC_DRAW, \
glGetAttribLocation, glEnableVertexAttribArray, glUniformMatrix4fv
# https://rdmilligan.wordpress.com/2016/09/03/opengl-vao-using-python/
class GlfwError(Exception):
pass
class Shader:
def __init__(self, code: str, stype):
self.id = shaders.compileShader(code, stype)
def __del__(self):
if hasattr(self, 'id'):
shaders.glDeleteShader(self.id)
@classmethod
def load(cls, filepath, stype):
with open(filepath, 'r') as fp:
return cls(fp.read(), stype)
class Program:
def __init__(self, vs: Shader, fs: Shader):
self.vs = vs
self.fs = fs
self.id = shaders.compileProgram(vs.id, fs.id, validate=False)
shaders.glUseProgram(self.id)
def __del__(self):
del self.vs
del self.fs
def uniform(self, name):
return shaders.glGetUniformLocation(self.id, name)
def attribute(self, name):
return shaders.glGetAttribLocation(self.id, name)
def send_attr(self, name, vertex, total_size,
step=3, dtype=GL_FLOAT, normalize=GL_FALSE) -> int:
position = shaders.glGetAttribLocation(self.id, name)
if position < 0:
raise ValueError(f'{position} {name}')
glVertexAttribPointer(position, step, dtype, normalize, total_size, vertex)
glEnableVertexAttribArray(position)
return position
def send_matrix(self, name, matrix, func=glUniformMatrix4fv):
position = shaders.glGetUniformLocation(self.id, name)
if position < 0:
raise ValueError(f'{position} {name} in {self.id}')
return func(position, 1, GL_FALSE, matrix)
class Buffer:
def __init__(self, kind=GL_ARRAY_BUFFER):
self.id = glGenBuffers(1)
self.kind = kind
def send_vertices(self, vertices):
vertices = np.array(vertices, np.float32)
glBindBuffer(GL_ARRAY_BUFFER, self.id)
glBufferData(self.kind, len(vertices) * 4, vertices, GL_STATIC_DRAW)
# glBindBuffer(GL_ARRAY_BUFFER, self.id)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)
return self
def __del__(self):
glDeleteBuffers(1, [self.id])
class Vao:
def __init__(self, vertices: np.ndarray):
self.vbo = Buffer().send_vertices(vertices)
self.id = glGenVertexArrays(1)
glBindVertexArray(self.id)
glBindBuffer(GL_ARRAY_BUFFER, self.vbo.id)
def __del__(self):
glDeleteBuffers(1, [self.id])
class GlWindow:
def __init__(self, w, h, title: str):
self.window = glfw.create_window(w, h, title, None, None)
self.height = h
self.width = w
if not self.window:
raise GlfwError
def run_loop(self, *args, **kwargs) -> None:
glfw.make_context_current(self.window)
while not glfw.window_should_close(self.window):
glfw.poll_events()
self.render()
glfw.swap_buffers(self.window)
def render(self, *args, **kwargs) -> None:
pass
@property
def ratio(self):
return self.width / self.height
def vec_iter(vec_list, vsize=3):
i = 0
m = len(vec_list)
while i < m:
point = vec_list[i:i + vsize]
yield point
i += vsize
def main():
if not glfw.init():
return
print(glfw.get_version_string())
window = GlWindow(640, 480, 'Hello world')
glfw.make_context_current(window.window)
vao = Vao((10.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 10.0))
program = Program(
Shader.load('vs.glsl', shaders.GL_VERTEX_SHADER),
Shader.load('fs.glsl', shaders.GL_FRAGMENT_SHADER)
)
# two tringles making a square.
plane = (
0.0, 0.0, 0.0,
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0
)
matrix_projection = Matrix44.perspective_projection(75, window.ratio, 1, 1000)
matrix_move = Matrix44.identity()
print(matrix_projection)
print(matrix_move)
program.send_attr('vertex', plane, step=3, total_size=len(plane) * 3)
program.send_matrix('projection', matrix_projection)
window.run_loop()
glfw.terminate()
if __name__ == "__main__":
main()