/
CLCanvas.py
304 lines (222 loc) · 9 KB
/
CLCanvas.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
__author__ = 'Marc de Klerk'
import os, sys
from PyQt4 import QtCore, QtGui, QtOpenGL
import numpy as np
import pyopencl as cl
from pyopencl.tools import get_gl_sharing_context_properties
from Buffer2D import Buffer2D
from Image2D import Image2D
from clutil import roundUp, createProgram
try:
from OpenGL.GL import *
except ImportError:
app = QtGui.QApplication(sys.argv)
QtGui.QMessageBox.critical(None, "Application Error",
"error importing PyOpenGL")
sys.exit(1)
from OpenGL.raw.GL.VERSION.GL_1_5 import glBufferData as rawGlBufferData
cm = cl.mem_flags
szFloat = np.dtype(np.float32).itemsize
szInt = np.dtype(np.int32).itemsize
LWORKGROUP = (16, 16)
class Filter:
def __init__(self, canvas):
pass
class CLCanvas(QtOpenGL.QGLWidget):
class Layer:
def __init__(self, clobj, pos=None, enabled=True, opacity=1.0,
filters=[]):
self.clobj = clobj
self.opacity = opacity if opacity != None else 1.0
self.enabled = enabled
self.pos = pos
self.filters = filters
def __init__(self, shape, parent=None):
super(CLCanvas, self).__init__(parent)
self.w = 0
self.pbo = None
self.tex = None
self.width = shape[0]
self.height = shape[1]
self.shape = shape
self.zoom = 1.0
self.transX = 0
self.transY = 1
self.flag = 0
self.viewport = None
self.resize(self.zoom * self.width, self.zoom * self.height)
self.initializeGL()
self.initCL()
self.installEventFilter(self)
self.fbo = glGenFramebuffers(1)
self.rbos = glGenRenderbuffers(2)
self.rbosCL = [None, None]
for i in [0, 1]:
glBindRenderbuffer(GL_RENDERBUFFER, self.rbos[i])
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA, self.width,
self.height)
self.rbosCL[i] = cl.GLRenderBuffer(self.context, cm.READ_WRITE,
int(self.rbos[i]))
self.rboRead = 0
self.rboWrite = 1
self.buffers = {}
self.layers = []
self.devices = self.context.get_info(cl.context_info.DEVICES)
self.queue = cl.CommandQueue(self.context,
properties=cl.command_queue_properties.PROFILING_ENABLE)
filename = os.path.join(os.path.dirname(__file__), 'clcanvas.cl')
program = createProgram(self.context, self.devices, [], filename)
self.kernBlendImgf = cl.Kernel(program, 'blend_imgf')
self.kernBlendBufui = cl.Kernel(program, 'blend_bufui')
self.kernBlendImgui = cl.Kernel(program, 'blend_imgui')
self.kernFlip = cl.Kernel(program, 'flip')
self.queue.finish()
glFinish()
def addLayer(self, clobj, opacity=None, filters=[]):
if opacity == None:
opacity = 1.0
if type(clobj) == cl.Image:
clobj.dim = (clobj.get_image_info(cl.image_info.WIDTH),
clobj.get_image_info(cl.image_info.HEIGHT))
layer = CLCanvas.Layer(clobj, opacity=opacity, filters=filters)
self.layers.append(layer)
return layer
def initCL(self):
platforms = cl.get_platforms()
if sys.platform == "darwin":
self.context = cl.Context(
properties=get_gl_sharing_context_properties(), devices=[])
else:
try:
properties = [(cl.context_properties.PLATFORM,
platforms)] + get_gl_sharing_context_properties()
self.context = cl.Context(properties)
except:
raise SystemError('Could not create OpenCL context')
self.queue = cl.CommandQueue(self.context)
def paintRenderBuffer(self):
pass
def setZoom(self, value):
self.zoom = value
self.resize(self.zoom * self.width, self.zoom * self.height)
def setPbo(self, pbo):
self.pbo = pbo
def minimumSizeHint(self):
return QtCore.QSize(self.zoom * self.width, self.zoom * self.height)
def initializeGL(self):
self.makeCurrent()
glClearColor(0.0, 0.0, 0.0, 0.0)
def swapRbos(self):
self.rboRead = not self.rboRead
self.rboWrite = not self.rboWrite
def paintEvent(self, event):
r = event.rect()
self.transX = -r.x()
self.transY = -int(self.zoom * self.height - r.height()) + r.y()
self.viewport = (r.width(), r.height())
self.rect = event.rect()
self.makeCurrent()
self.paintGL()
if self.doubleBuffer():
self.swapBuffers()
glFlush()
def paintGL(self):
if len(self.layers) == 0:
return
#clear the read renderbuffer
glBindRenderbuffer(GL_RENDERBUFFER, self.rbos[self.rboRead])
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, self.fbo)
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_RENDERBUFFER, self.rbos[self.rboRead])
glClear(GL_COLOR_BUFFER_BIT)
cl.enqueue_acquire_gl_objects(self.queue, self.rbosCL)
visible = []
for layer in self.layers:
if not layer.enabled or layer.opacity == 0:
continue
visible.append(layer)
# if layer.opacity == 1.0:
# break
i = 0
for layer in reversed(visible):
input = layer.clobj
for filter in layer.filters:
input = filter.execute(self.queue, input)
args = [
cl.Sampler(self.context, False, cl.addressing_mode.NONE,
cl.filter_mode.NEAREST),
self.rbosCL[self.rboRead],
self.rbosCL[self.rboWrite],
np.float32(layer.opacity),
input
]
if type(input) == Image2D:
if (input.format.channel_order,
input.format.channel_data_type) == (
cl.channel_order.RGBA, cl.channel_type.UNORM_INT8):
self.kernBlendImgf(self.queue, input.dim, LWORKGROUP,
*args).wait()
elif (input.format.channel_order,
input.format.channel_data_type) == (
cl.channel_order.RGBA, cl.channel_type.UNSIGNED_INT8):
self.kernBlendImgui(self.queue, input.dim, LWORKGROUP,
*args).wait()
else:
raise NotImplementedError()
elif type(input) == Buffer2D:
args.append(np.array(input.dim, np.int32))
if input.dtype == np.uint32:
self.kernBlendBufui(self.queue, input.dim, LWORKGROUP,
*args).wait()
else:
raise NotImplementedError()
else:
raise NotImplementedError()
self.queue.finish()
self.swapRbos()
i += 1
cl.enqueue_release_gl_objects(self.queue, self.rbosCL)
gw = roundUp(self.shape, LWORKGROUP)
args = [
self.rbosCL[self.rboRead],
self.rbosCL[self.rboWrite],
cl.Sampler(self.context, False, cl.addressing_mode.NONE,
cl.filter_mode.NEAREST),
]
self.kernFlip(self.queue, gw, LWORKGROUP, *args)
self.queue.finish()
#Prepare to render into the renderbuffer
glBindRenderbuffer(GL_RENDERBUFFER, self.rbos[self.rboWrite])
glBindFramebuffer(GL_READ_FRAMEBUFFER, self.fbo)
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_RENDERBUFFER, self.rbos[self.rboWrite])
#Set up to read from the renderbuffer and draw to window-system framebuffer
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(0, 0, self.viewport[0], self.viewport[1])
#Do the copy
glBlitFramebuffer(
int(self.rect.x() / self.zoom),
self.height - int((self.rect.y() + self.rect.height()) / self.zoom),
int((self.rect.x() + self.rect.width()) / self.zoom),
self.height - int(self.rect.y() / self.zoom),
0, 0, self.rect.width(), self.rect.height(), GL_COLOR_BUFFER_BIT,
GL_NEAREST);
def eventFilter(self, object, event):
if hasattr(self, 'mouseDrag') and\
(
event.type() == QtCore.QEvent.MouseMove and event.buttons() == QtCore.Qt.LeftButton):
point = (
int(event.pos().x() / self.zoom),
int(event.pos().y() / self.zoom))
self.mouseDrag(self.lastMousePos, point)
self.lastMousePos = point
return True
if hasattr(self,
'mousePress') and event.type() == QtCore.QEvent.MouseButtonPress:
point = (
int(event.pos().x() / self.zoom),
int(event.pos().y() / self.zoom))
self.mousePress(point)
self.lastMousePos = point
return True
return False