-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17_vertex_buffer_objects.py
415 lines (325 loc) · 12.9 KB
/
17_vertex_buffer_objects.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
from PySide2 import QtWidgets, QtGui, QtCore
import cv2
import numpy as np
import OpenGL.GL as gl
import OpenGL.GLU as glu
import sys
import array
def power_of_two(num: int):
if num != 0:
num -= 1
num |= (num >> 1) # Or first 2 bits
num |= (num >> 2) # Or next 2 bits
num |= (num >> 4) # Or next 4 bits
num |= (num >> 8) # Or next 8 bits
num |= (num >> 16) # Or next 16 bits
num += 1
return num
class MutableNamedTuple(object):
__slots__ = []
def __init__(self, *args):
for idx, name in enumerate(self.__slots__):
setattr(self, name, args[idx])
def __iter__(self):
for name in self.__slots__:
yield getattr(self, name)
class Rect(MutableNamedTuple):
__slots__ = ['x', 'y', 'w', 'h']
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
class VertexPos2D(MutableNamedTuple):
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
class Texture(object):
def __init__(self):
self.tid = 0
self.width = 0
self.height = 0
self.pixels = None
self.channels = 0
self.image_width = 0
self.image_height = 0
self.filtering = gl.GL_LINEAR
self.default_texture_wrap = gl.GL_REPEAT
def loadTextureFromPixels(self):
if self.tid == 0 and self.pixels is not None:
self.height = self.pixels.shape[0]
self.width = self.pixels.shape[1]
self.tid = gl.glGenTextures(1)
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tid)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, self.tid)
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, self.store_type, self.width,
self.height, 0, self.pixel_type,
gl.GL_UNSIGNED_BYTE, self.pixels)
self.applyTextureFiltering(bind=False)
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
error = gl.glGetError()
if error != gl.GL_NO_ERROR:
print('Error loading pixels from image! %s' %
glu.gluErrorString(error), file=sys.stderr)
return False
else:
print('Cannot load texture from current pixels', file=sys.stderr)
if self.tid != 0:
print('A texture is already loaded', file=sys.stderr)
elif self.pixels is None:
print('No pixels to create Textures from!', file=sys.stderr)
return False
return True
def power_of_two(self, num: int):
if num != 0:
num -= 1
num |= (num >> 1) # Or first 2 bits
num |= (num >> 2) # Or next 2 bits
num |= (num >> 4) # Or next 4 bits
num |= (num >> 8) # Or next 8 bits
num |= (num >> 16) # Or next 16 bits
num += 1
return num
def loadTextureFromFile(self, path, with_alpha=True):
if not self.loadPixelsFromFile(path, with_alpha=with_alpha):
return False
return self.loadTextureFromPixels()
def loadPixelsFromFile(self, path, with_alpha=True):
self.pixels = cv2.imread(
path,
cv2.IMREAD_UNCHANGED if with_alpha else cv2.IMREAD_COLOR)
if self.pixels is None:
print('Unable to load image from %s' % path, file=sys.stderr)
return False
self.channels = self.pixels.shape[2] if len(
self.pixels.shape) > 2 else 1
if self.channels not in (3, 4):
print('Given image is not supported')
return False
if self.channels == 3:
self.pixel_type = gl.GL_BGR
self.store_type = gl.GL_RGB
elif self.channels == 4:
self.pixel_type = gl.GL_BGRA
self.store_type = gl.GL_RGBA
self.image_height = self.pixels.shape[0]
self.image_width = self.pixels.shape[1]
self.pixels = cv2.copyMakeBorder(
self.pixels,
0,
power_of_two(self.pixels.shape[0]) - self.pixels.shape[0],
0,
power_of_two(self.pixels.shape[1]) - self.pixels.shape[1],
cv2.BORDER_CONSTANT, value=(255, 0, 0))
return True
def loadTextureFromFileWithColorKey(
self, path, color_key=(0, 0, 0, 255)):
if not self.loadPixelsFromFile(path):
return False
np.where(self.pixels == color_key, (0, 0, 0, 0), self.pixels)
cv2.bitwise_and(self.pixels, self.pixels, mask=self.pixels[:, :, 3])
return self.loadTextureFromPixels()
def freeTexture(self):
# Delete Texture
if self.tid != 0:
gl.glDeleteTextures(1, self.tid)
self.tid = 0
self.pixels = None
self.height = self.width = 0
self.image_height = self.image_height = 0
def render(self, x, y, clip: Rect = None):
if self.tid != 0:
self.applyTextureFiltering()
tex_top = tex_left = 0.0
tex_bottom = self.image_height / self.height
tex_right = self.image_width / self.width
quad_width, quad_height = self.image_width, self.image_height
if clip is not None:
tex_left = clip.x / self.width
tex_right = (clip.x + clip.w) / self.width
tex_top = clip.y / self.height
tex_bottom = (clip.y + clip.h) / self.height
quad_width, quad_height = clip.w, clip.h
gl.glTranslatef(x + quad_width/2, y + quad_height/2, 0)
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tid)
# Render texture quad
gl.glBegin(gl.GL_QUADS)
gl.glTexCoord2f(tex_left, tex_top)
gl.glVertex2f(-quad_width/2, -quad_height/2)
gl.glTexCoord2f(tex_right, tex_top)
gl.glVertex2f(quad_width/2, -quad_height/2)
gl.glTexCoord2f(tex_right, tex_bottom)
gl.glVertex2f(quad_width/2, quad_height/2)
gl.glTexCoord2f(tex_left, tex_bottom)
gl.glVertex2f(-quad_width/2, quad_height/2)
gl.glEnd()
def lock(self):
if self.pixels is None and self.tid != 0:
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tid)
self.pixels = gl.glGetTexImage(
gl.GL_TEXTURE_2D, 0, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE)
self.pixels = np.frombuffer(self.pixels, dtype='uint8').reshape(
self.width, self.height, self.channels)
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
return True
return False
def unlock(self):
if self.pixels is not None and self.tid != 0:
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tid)
gl.glTexSubImage2D(
gl.GL_TEXTURE_2D, 0, 0, 0, self.width, self.height,
gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, self.pixels)
self.pixels = np.array(self.pixels)
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
def applyTextureFiltering(self, bind=True):
if bind:
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tid)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
self.filtering)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
self.filtering)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S,
self.default_texture_wrap)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T,
self.default_texture_wrap)
if bind:
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.button = QtWidgets.QPushButton('Test', self)
self.widget = GLWidget(self)
self.mainLayout = QtWidgets.QHBoxLayout()
self.mainLayout.addWidget(self.widget)
self.setLayout(self.mainLayout)
def keyPressEvent(self, event: QtGui.QKeyEvent):
if event.key() == QtCore.Qt.Key_Q:
self.widget.wrap_type += 1
super().keyPressEvent(event)
class GLWidget(QtWidgets.QOpenGLWidget):
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_FPS = 600
def __init__(self, parent):
super().__init__(parent)
self.texture = Texture()
self.texX = self.texY = 0
self._wraptype = 0
# self.start_timer()
self.quad_vertices = array.array('f')
self.indices = array.array('I')
self.vertex_buffer = 0
self.index_buffer = 0
array.typecodes
def update(self):
self.texX += 1
self.texY += 1
if self.texX >= self.texture.width:
self.texX = 0
if self.texY >= self.texture.height:
self.texY = 0
super().update()
@property
def wrap_type(self):
return self._wraptype
@wrap_type.setter
def wrap_type(self, value):
self._wraptype = value
if self._wraptype >= 5:
self._wraptype = 0
if self._wraptype == 0:
self.texture.default_texture_wrap = gl.GL_REPEAT
elif self._wraptype == 1:
self.texture.default_texture_wrap = gl.GL_CLAMP
elif self._wraptype == 2:
self.texture.default_texture_wrap = gl.GL_CLAMP_TO_BORDER
elif self._wraptype == 3:
self.texture.default_texture_wrap = gl.GL_CLAMP_TO_EDGE
elif self._wraptype == 4:
self.texture.default_texture_wrap = gl.GL_MIRRORED_REPEAT
def start_timer(self):
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.update)
self.timer.start(1000/self.SCREEN_FPS)
def minimumSizeHint(self):
return QtCore.QSize(self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
def sizeHint(self):
return QtCore.QSize(self.SCREEN_WIDTH, self.SCREEN_HEIGHT)
def getOpenglInfo(self):
info = """
Vendor: {0}
Renderer: {1}
OpenGL Version: {2}
Shader Version: {3}
""".format(
gl.glGetString(gl.GL_VENDOR),
gl.glGetString(gl.GL_RENDERER),
gl.glGetString(gl.GL_VERSION),
gl.glGetString(gl.GL_SHADING_LANGUAGE_VERSION)
)
return info
def loadMedia(self):
self.quad_vertices.extend(VertexPos2D(
self.SCREEN_WIDTH * 1/4, self.SCREEN_HEIGHT * 1/4))
self.quad_vertices.extend(VertexPos2D(
self.SCREEN_WIDTH * 3/4, self.SCREEN_HEIGHT * 1/4))
self.quad_vertices.extend(VertexPos2D(
self.SCREEN_WIDTH * 3/4, self.SCREEN_HEIGHT * 3/4))
self.quad_vertices.extend(VertexPos2D(
self.SCREEN_WIDTH * 1/4, self.SCREEN_HEIGHT * 3/4))
self.indices.extend(range(4))
self.vertex_buffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, self.quad_vertices.tobytes(),
gl.GL_STATIC_DRAW)
self.index_buffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.index_buffer)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.indices.tobytes(),
gl.GL_STATIC_DRAW)
return True
def initializeGL(self):
print(self.getOpenglInfo())
self.loadMedia()
# initialize projection matrix
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT, 0, -1, 1)
# Initialize modelview matrix
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glLoadIdentity()
# initializeGL clear color
gl.glClearColor(0, 1, 0, 1)
gl.glEnable(gl.GL_TEXTURE_2D)
# Set blending
gl.glEnable(gl.GL_BLEND)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
error = gl.glGetError()
if error != gl.GL_NO_ERROR:
print("Error Iniitalizing OpenGL! %s" % glu.gluErrorString(error),
file=sys.strderr)
return False
return True
def paintGL(self):
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_buffer)
gl.glVertexPointer(2, gl.GL_FLOAT, 0, None)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.index_buffer)
gl.glDrawElements(gl.GL_QUADS, 4, gl.GL_UNSIGNED_INT, None)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
gl.glFlush()
def moveCameraX(self, value):
self.camera_x += value
def moveCameraY(self, value):
self.camera_y += value
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()