-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglPlotLib.py
3085 lines (2381 loc) · 105 KB
/
glPlotLib.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''GPU accelerated graphics and plotting using PyOpenGL.
This file is part of the EARS project <https://github.com/nalamat/ears>
Copyright (C) 2017-2021 Nima Alamatsaz <nima.alamatsaz@gmail.com>
'''
'''
Notes:
- GL color range is 0-1, Qt color range is 0-255
- Qt window dimensions are normalized by the device pixel ratio, i.e. a
800x600 window looks almost the same on both low and high DPI screens.
this causes an issue that texts drawn with QPainter without adjusting for
pixel ratio will look pixelated on high DPI.
- OpenGL coordinates in fragment shader are actual screen pixel values and
must be normalized manually if necessary. Look at getPixelRatio().
Marker types:
0 1 2 3 4 5 6 7 8 9 10
◼ ◻ + x * ● ○ ▼ ▲ ◀ ▶
'''
import sys
import math
import time
import logging
import functools
import threading
import collections
import numpy as np
import scipy as sp
import datetime as dt
from scipy import signal
from PyQt5 import QtCore, QtGui, QtWidgets
from ctypes import sizeof, c_void_p, c_bool, c_uint, c_float, string_at
from OpenGL.GL import *
import misc
import pypeline
log = logging.getLogger(__name__)
sizeFloat = sizeof(c_float)
GL_VERSION = (4, 1)
GL_SAMPLES = 0
MAX_CHANNELS = 128
MAX_3D_TEXTURE_SIZE = 1024
defaultColors = np.array([
[0 , 0 , .3 , 1], # 1
[0 , 0 , .55, 1], # 2
[0 , 0 , .7 , 1], # 3
[0 , 0 , 1 , 1], # 4
[0 , .3 , 0 , 1], # 5
[0 , .45, 0 , 1], # 6
[0 , .6 , 0 , 1], # 7
[0 , .75, 0 , 1], # 8
[0 , .85, 0 , 1], # 9
[0 , 1 , 0 , 1], # 10
[.3, 0 , 0 , 1], # 11
[.6, 0 , 0 , 1], # 12
[1 , 0 , 0 , 1], # 13
[1 , .4 , 0 , 1], # 14
[1 , .6 , 0 , 1], # 15
[1 , .8 , 0 , 1], # 16
[.9, .9 , 0 , 1], # 17
[0 , .4 , .4 , 1], # 18
[0 , .6 , .6 , 1], # 19
[0 , .8 , .8 , 1], # 20
[.4, 0 , .4 , 1], # 21
[.7, 0 , .7 , 1], # 22
[1 , 0 , 1 , 1], # 23
[0 , 0 , 0 , 1], # 24
[.2, .2 , .2 , 1], # 25
[.4, .4 , .4 , 1], # 26
[.6, .6 , .6 , 1], # 27
[.8, .8 , .8 , 1], # 28
], dtype=np.float32)
def getPixelRatio():
'''Use for high DPI display support.
For example, retina displays have a pixel ratio of 2.0.
'''
#
# try:
# return QtWidgets.QApplication.topLevelWidgets()[0].window() \
# .windowHandle().screen().devicePixelRatio()
# except:
return QtWidgets.QApplication.screens()[-1].devicePixelRatio()
# return QtWidgets.QApplication.primaryScreen().devicePixelRatio()
def setSurfaceFormat():
'''Set Qt surface format: samples, profile and version.
On macOS surface format must be set before running a Qt application.
'''
surfaceFormat = QtGui.QSurfaceFormat()
surfaceFormat.setSamples(GL_SAMPLES)
surfaceFormat.setProfile(QtGui.QSurfaceFormat.CoreProfile)
surfaceFormat.setMajorVersion(GL_VERSION[0])
surfaceFormat.setMinorVersion(GL_VERSION[1])
QtGui.QSurfaceFormat.setDefaultFormat(surfaceFormat)
class Program:
'''OpenGL shader program.
Contex manager for binding and unbinding the GL program and its VAO.
Convenience methods for modifying uniforms, VBOs and an EBO.
Helper functions in GLSL such as 2D transformation, random number
generation, sinusoidal ramp function, and marker symbol generation.
'''
_helperFunctions = '''
const float PI = 3.14159265359;
vec2 transform(vec2 p, vec2 a, vec2 b) {
return a*p + b;
}
vec2 transform(vec2 p, float ax, float ay, float bx, float by) {
return transform(p, vec2(ax, ay), vec2(bx, by));
}
float rand(vec2 seed) {
return fract(sin(dot(seed.xy, vec2(12.9898,78.233))) * 43758.5453);
}
bool between(float a, float b, float c) {
return a <= b && b < c;
}
bool between(int a, int b, int c) {
return a <= b && b < c;
}
float sinFade(float fade) {
return sin((fade*2 - 1) * PI/2) / 2 + .5;
}
'''
_markerFunction = '''
float markerAlpha(vec2 point, float size, int type) {
// NDC point coordinate (-1 to +1)
point = 2 * (point - .5);
float point2 = dot(point, point); // square distance from origin
float pxl = 2 / size; // pixel size in NDC point coord
float a = 1;
switch (type) {
case 0: // full square
a = 1;
break;
case 1: // hollow square
a = step(1 - pxl, abs(point.y)) - step(1, abs(point.y)) +
step(1 - pxl, abs(point.x)) - step(1, abs(point.x));
a = clamp(a, 0, 1);
break;
case 2: // +
a = step(-pxl/2, point.y) - step(pxl/2, point.y) +
step(-pxl/2, point.x) - step(pxl/2, point.x);
a = clamp(a, 0, 1);
break;
case 3: // x
a = smoothstep(-pxl, 0, abs(point.y) - abs(point.x)) -
smoothstep(0, pxl, abs(point.y) - abs(point.x));
break;
case 4: // *
a = (step(-pxl/2, point.y) - step(pxl/2, point.y) +
step(-pxl/2, point.x) - step(pxl/2, point.x) +
smoothstep(-pxl, 0, abs(point.y) - abs(point.x)) -
smoothstep(0, pxl, abs(point.y) - abs(point.x))) *
step(point2, 1);
a = clamp(a, 0, 1);
break;
default:
case 5: // full circle
// note: no performance difference with step vs smoothstep
float r0 = 1;
float r1 = 1 - 1 * pxl;
a = 1 - smoothstep(r1 * r1, r0 * r0, point2);
break;
case 6: // hollow circle
float r2 = 1 - 2 * pxl;
a = smoothstep(r2 * r2, r1 * r1, point2) -
smoothstep(r1 * r1, r0 * r0, point2);
break;
case 7: // down triangle
a = 1 - smoothstep(-pxl, 0, point.y + abs(point.x * 2) - 1);
break;
case 8: // up triangle
a = smoothstep(0, pxl, point.y - abs(point.x * 2) + 1);
break;
case 9: // left triangle
a = smoothstep(0, pxl, point.x - abs(point.y * 2) + 1);
break;
case 10: // right triangle
a = 1 - smoothstep(-pxl, 0, point.x + abs(point.y * 2) - 1);
break;
}
return a;
}
'''
@classmethod
def createShader(cls, shaderType, source):
"""Compile a shader."""
source = ('#version %d%d0 core\n' % GL_VERSION) + \
cls._helperFunctions + source
shader = glCreateShader(shaderType)
glShaderSource(shader, source)
glCompileShader(shader)
if glGetShaderiv(shader, GL_COMPILE_STATUS) != GL_TRUE:
raise RuntimeError(glGetShaderInfoLog(shader))
return shader
def __init__(self, vert=None, tesc=None, tese=None, geom=None, frag=None,
comp=None):
'''
Args:
vert (str): Vertex shader code (required).
tesc (str): Tesselation control shader code (optional).
tese (str): Tesselation evaluation shader code (optional).
geom (str): Geometry shader code (optional).
frag (str): Framgent shader code (mandatory).
comp (str): Compute shader code. Can't be used with other shader.
'''
if (vert or tesc or tese or geom or frag) and not (vert and frag):
raise ValueError('Require both vertex and fragment shaders')
if (vert or tessc or tesse or geom or frag) and comp:
raise ValueError('Compute shader cannot be linked with others')
if vert: vert = Program.createShader(GL_VERTEX_SHADER , vert)
if tesc: tesc = Program.createShader(GL_TESS_CONTROL_SHADER , tesc)
if tese: tese = Program.createShader(GL_TESS_EVALUATION_SHADER, tese)
if geom: geom = Program.createShader(GL_GEOMETRY_SHADER , geom)
if frag: frag = Program.createShader(GL_FRAGMENT_SHADER , frag)
if comp: comp = Program.createShader(GL_COMPUTE_SHADER , comp)
self.id = glCreateProgram()
if vert: glAttachShader(self.id, vert)
if tesc: glAttachShader(self.id, tesc)
if tese: glAttachShader(self.id, tese)
if geom: glAttachShader(self.id, geom)
if frag: glAttachShader(self.id, frag)
if comp: glAttachShader(self.id, comp)
glLinkProgram(self.id)
if glGetProgramiv(self.id, GL_LINK_STATUS) != GL_TRUE:
raise RuntimeError(glGetProgramInfoLog(self.id))
if vert: glDeleteShader(vert)
if tesc: glDeleteShader(tesc)
if tese: glDeleteShader(tese)
if geom: glDeleteShader(geom)
if frag: glDeleteShader(frag)
if comp: glDeleteShader(comp)
self.vao = glGenVertexArrays(1)
self.vbos = {}
self.ebo = None
self._contexts = 0
def __enter__(self):
if not self._contexts:
self.begin()
self._contexts += 1
def __exit__(self, *args):
self._contexts -= 1
if not self._contexts:
self.end()
def begin(self):
glUseProgram(self.id)
glBindVertexArray(self.vao)
def end(self):
glBindVertexArray(0)
glUseProgram(0)
def setUniform(self, name, type, value):
with self:
if not isinstance(value, collections.abc.Iterable):
value = (value,)
id = glGetUniformLocation(self.id, name)
globals()['glUniform' + type](id, *value)
def setVBO(self, name, type, size, data, usage):
'''Copy vertex data to a VBO and link to its vertex attribute.
Args:
name (str): As defined in the shader.
type (int): Of each component, e.g. GL_BYTE, GL_INT, GL_FLOAT
size (int): Number of components per vertex.
data (np.ndarray): Vertex data.
usage (int): Expected usage pattern, e.g. GL_STATIC_DRAW,
GL_DYNAMIC_DRAW, GL_STREAM_DRAW
'''
with self:
if name not in self.vbos: self.vbos[name] = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, self.vbos[name])
glBufferData(GL_ARRAY_BUFFER, data, usage)
loc = glGetAttribLocation(self.id, name)
glVertexAttribPointer(loc, size, type, GL_FALSE, 0, c_void_p(0))
glEnableVertexAttribArray(loc)
def subVBO(self, name, offset, data):
glBindBuffer(GL_ARRAY_BUFFER, self.vbos[name])
glBufferSubData(GL_ARRAY_BUFFER, offset, data)
def setEBO(self, data, usage):
with self:
if not self.ebo: self.ebo = glGenBuffers(1)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.ebo)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, data, usage)
class Item:
'''Base graphical item capable of containing child items.'''
@property
def canvas(self):
if self.parent:
return self.parent.canvas
else:
return None
def __init__(self, parent, **kwargs):
'''
Args:
parent (Item): Has to be another graphical item.
pos (2 floats): Item position in unit (0-1) parent space (x, y).
size (2 floats): Item size in unit (0-1) parent space (w, h).
margin (4 floats): Margin in pixels (l, t, r, b).
bgColor (4 floats): Backgoround color. RGBA 0-1.
fgColor (4 floats): Foreground color for border and texts. RGBA 0-1.
'''
# properties with their default values
defaults = dict(pos=(0,0), size=(1,1), margin=(0,0,0,0),
bgColor=(1,1,1,0), fgColor=(0,0,0,1), visible=True)
self._initProps(defaults, kwargs)
super().__init__()
self._props['parent'] = parent
self._props['posPxl'] = np.array([0, 0])
self._props['sizePxl'] = np.array([1, 1])
self._initialized = False
self._items = []
if isinstance(self.parent, Item):
self.parent.addItem(self)
def _initProps(self, defaults, kwargs):
''' Initialize properties with the given or default values.
Setter monitoring (refreshing, etc) won't apply here.
'''
if not hasattr(self, '_props'):
self._props = dict()
for name, default in defaults.items():
if name in self._props:
continue
elif name in kwargs:
self._props[name] = kwargs[name]
else:
self._props[name] = default
def __getattr__(self, name):
if name != '_props' and hasattr(self, '_props') and name in self._props:
return self._props[name]
else:
return super().__getattribute__(name)
def __setattr__(self, name, value):
if name in {'parent', 'posPxl', 'sizePxl'}:
raise AttributeError('Cannot set attribute')
if name != '_props' and hasattr(self, '_props') and name in self._props:
self._props[name] = value
if name in {'pos', 'size', 'margin'}:
self.resizeGL()
else:
super().__setattr__(name, value)
def addItem(self, item):
if not isinstance(item, Item):
raise TypeError('`item` should be an Item')
self._items += [item]
def callItems(self, func, *args, **kwargs):
for item in self._items:
if hasattr(item, func):
getattr(item, func)(*args, **kwargs)
# functions below are chained to all child items
# they are initially called from Canvas
def initializeGL(self):
self._initialized = True
self.callItems('initializeGL')
def resizeGL(self):
parent = self.parent
margin = np.array(self.margin)
self._props['posPxl'] = self.pos * parent.sizePxl + \
parent.posPxl + margin[[0,3]]
self._props['sizePxl'] = self.size * parent.sizePxl - \
margin[0:2] - margin[2:4]
self.callItems('resizeGL')
def paintGL(self):
if not self.visible: return
self.callItems('paintGL')
_funcs = ['wheelEvent']
for func in _funcs:
exec('def %(func)s(self, *args, **kwargs):\n'
' self.callItems("%(func)s", *args, **kwargs)' % {'func':func})
class Text(Item):
'''Graphical text item.'''
_vertShader = '''
in vec2 aVertex;
in vec2 aTexCoord;
out vec2 TexCoord;
uniform vec2 uPos; // unit
uniform vec2 uAnchor; // unit
uniform vec2 uSize; // pixels
uniform vec2 uParentPos; // pixels
uniform vec2 uParentSize; // pixels
uniform vec2 uCanvasSize; // pixels
void main() {
vec2 pos = (uPos * uParentSize + uParentPos) / uCanvasSize;
vec2 size = uSize / uCanvasSize;
gl_Position = vec4(
((aVertex - uAnchor) * size + pos) * 2 - vec2(1),
0, 1);
TexCoord = aTexCoord;
}
'''
_fragShader = '''
in vec2 TexCoord;
out vec4 FragColor;
uniform sampler2D uTexture;
void main() {
FragColor = texture(uTexture, TexCoord);
}
'''
@classmethod
def getSize(cls, text, font):
'''Get width and height of the given text in pixels'''
if not hasattr(cls, '_image'):
cls._image = QtGui.QImage(1, 1, QtGui.QImage.Format_ARGB32)
cls._painter = QtGui.QPainter()
cls._painter.begin(cls._image)
cls._painter.setFont(font)
rect = cls._painter.boundingRect(QtCore.QRect(),
QtCore.Qt.AlignLeft, text)
return rect.width(), rect.height()
def __init__(self, parent, **kwargs):
'''
Args:
text (str)
pos (2 floats): In unit parent space.
anchor (2 floats): In unit text space.
margin (4 ints): In pixels (l, t, r, b).
fontSize (float)
bold (bool)
italic (bool)
align (QtCore.Qt.Alignment): Possible values are AlignLeft,
AlignRight, AlignCenter, AlignJustify.
fgColor (4 floats): RGBA 0-1.
bgColor (4 floats): RGBA 0-1.
visible (bool)
'''
# properties with their default values
defaults = dict(text='', pos=(.5,.5), anchor=(.5,.5), margin=(0,0,0,0),
fontSize=12, bold=False, italic=False, align=QtCore.Qt.AlignCenter,
bgColor=(1,1,1,0), fgColor=(0,0,0,1))
self._initProps(defaults, kwargs)
super().__init__(parent, **kwargs)
def __setattr__(self, name, value):
super().__setattr__(name, value)
if not hasattr(self, '_initialized') or not self._initialized: return
if name != '_uProps' and hasattr(self, '_uProps') and \
name in self._uProps:
self._prog.setUniform(*self._uProps[name], value)
if name in {'text', 'margin', 'fontSize', 'bold', 'italic',
'align', 'bgColor', 'fgColor'}:
self.refresh()
def initializeGL(self):
vertices = np.array([
[0, 0],
[0, 1],
[1, 1],
[1, 0],
], dtype=np.float32)
indices = np.array([
[0,1,3],
[1,2,3],
], dtype=np.uint32)
texCoords = np.array([
[0, 1],
[0, 0],
[1, 0],
[1, 1],
], dtype=np.float32)
self._tex = glGenTextures(1)
self._prog = Program(vert=self._vertShader, frag=self._fragShader)
# properties linked with a uniform variable in the shader
self._uProps = dict(pos=('uPos', '2f'), anchor=('uAnchor', '2f'))
with self._prog:
for name, value in self._uProps.items():
self._prog.setUniform(*value, self._props[name])
self._prog.setVBO('aVertex', GL_FLOAT, 2, vertices, GL_STATIC_DRAW)
self._prog.setVBO('aTexCoord', GL_FLOAT, 2, texCoords,
GL_STATIC_DRAW)
self._prog.setEBO(indices, GL_STATIC_DRAW)
self.refresh()
super().initializeGL()
def resizeGL(self):
super().resizeGL()
with self._prog:
self._prog.setUniform('uParentPos', '2f', self.parent.posPxl)
self._prog.setUniform('uParentSize', '2f', self.parent.sizePxl)
self._prog.setUniform('uCanvasSize', '2f', self.canvas.sizePxl)
def refresh(self):
'''Generates texture for the given text, font, color, etc.
Note: This function does not force redrawing of the text on screen.
'''
ratio = getPixelRatio()
margin = (np.array(self.margin) * ratio).astype(np.int)
font = QtGui.QFont('arial', int(self.fontSize * ratio),
QtGui.QFont.Bold if self.bold else QtGui.QFont.Normal, self.italic)
w, h = Text.getSize(self.text, font)
w += margin[0] + margin[2]
h += margin[1] + margin[3]
if w==0: w += 1
if h==0: h += 1
image = QtGui.QImage(w, h, QtGui.QImage.Format_ARGB32)
image.fill(QtGui.QColor(*np.array(self.bgColor)*255))
painter = QtGui.QPainter()
painter.begin(image)
painter.setPen(QtGui.QColor(*(np.array(self.fgColor)*255).astype(int)))
painter.setFont(font)
painter.drawText(margin[0], margin[1],
w - margin[0] - margin[2], h - margin[1] - margin[3],
self.align, self.text)
painter.end()
str = image.bits().asstring(w * h * 4)
texData = np.frombuffer(str, dtype=np.uint8).reshape((h, w, 4))
self._prog.setUniform('uSize', '2f', (w/ratio, h/ratio))
# texture
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self._tex)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texData.shape[1],
texData.shape[0], 0, GL_BGRA, GL_UNSIGNED_BYTE, texData)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
# glGenerateMipmap(GL_TEXTURE_2D)
def paintGL(self):
if not self.visible: return
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self._tex)
with self._prog:
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, c_void_p(0))
super().paintGL()
class TextArray(Item):
'''Graphical text array item.'''
_vertShader = '''
in vec2 aPos; // of text instance in unit space
in vec2 aSize; // of text instance in pixels
out vec2 vPos; // same as aPos
out vec2 vSize; // same as aSize
out int vIndex; // gl_VertexID
uniform vec2 uPos; // of text array in parent's unit space
uniform vec2 uSize; // of text array in parent's unit space
uniform vec4 uMargin; // pixels: l t r b
uniform vec2 uOffset; // pixels
uniform vec2 uParentPos; // pixels
uniform vec2 uParentSize; // pixels
uniform vec2 uCanvasSize; // pixels
void main() {
// transform inside parent
vec2 pos = (uPos * uParentSize + uParentPos) / uCanvasSize;
vec2 size = uSize * uParentSize / uCanvasSize;
// add margin and offset
pos += (uMargin.xw + uOffset) / uCanvasSize;
size -= (uMargin.xy + uMargin.zw) / uCanvasSize;
// apply transformation to vertex and take to NDC space
gl_Position = vec4( (aPos * size + pos) * 2 - vec2(1), 0, 1);
vPos = aPos;
vSize = aSize;
vIndex = gl_VertexID;
}
'''
_geomShader = '''
layout (points) in;
layout (triangle_strip, max_vertices = 4) out;
in vec2 vPos[]; // of text instance in unit space
in vec2 vSize[]; // of text instance in pixels
in int vIndex[]; // gl_VertexID
out vec2 gPos; // of text instance in unit space
out vec2 gSize; // of text instance in pixels
out float gIndex; // gl_VertexID
out vec2 gTexCoord; // unit texture space
uniform vec2 uCanvasSize; // pixels
uniform vec2 uAnchor; // unit
void main() {
vec2 size = vSize[0] / uCanvasSize * 2; // pixels to NDC space
vec2 pos = gl_in[0].gl_Position.xy;
vec2 pos0 = pos - uAnchor * size;
vec2 pos1 = pos + (1 - uAnchor) * size;
gPos = vPos[0];
gSize = vSize[0];
gIndex = vIndex[0];
gl_Position = vec4(pos0.xy, 0, 1);
gTexCoord = vec2(0, 1);
EmitVertex();
gl_Position = vec4(pos0.x, pos1.y, 0, 1);
gTexCoord = vec2(0, 0);
EmitVertex();
gl_Position = vec4(pos1.x, pos0.y, 0, 1);
gTexCoord = vec2(1, 1);
EmitVertex();
gl_Position = vec4(pos1.x, pos1.y, 0, 1);
gTexCoord = vec2(1, 0);
EmitVertex();
}
'''
_fragShader = '''
in vec2 gPos;
in vec2 gSize;
in float gIndex;
in vec2 gTexCoord;
out vec4 FragColor;
uniform sampler3D uTexture;
uniform vec3 uTexSize;
uniform float uPixelRatio;
void main() {
vec3 texCoord = vec3(gTexCoord * gSize * uPixelRatio / uTexSize.zy,
(gIndex + .5) / uTexSize.x);
FragColor = texture(uTexture, texCoord);
}
'''
def __init__(self, parent, **kwargs):
'''
Args:
pos (2 floats): In unit parent space.
size (2 floats): In unit parent space.
margin (4 ints): In pixels (l, t, r, b).
texts (n strs): Texts to be drawn.
poss (nx2 floats): Position of texts in unit TextArray space.
anchor (2 floats): In unit text instance space.
offset (2 floats): In pixels.
fontSize (float)
bold (bool)
italic (bool)
align (QtCore.Qt.Alignment): Possible values are AlignLeft,
AlignRight, AlignCenter, AlignJustify.
fgColor (nx4 floats): RGBA 0-1.
bgColor (4 floats): RGBA 0-1.
visible (bool)
'''
# properties with their default values
defaults = dict(texts=[], poss=[], anchor=(.5,.5), offset=(0,0),
fontSize=12, bold=False, italic=False, align=QtCore.Qt.AlignCenter,
bgColor=(1,1,1,0), fgColor=(0,0,0,1))
self._initProps(defaults, kwargs)
super().__init__(parent, **kwargs)
self.poss = self.poss
def __setattr__(self, name, value):
if name == 'texts' and isinstance(value, str):
value = [value]
if name == 'poss':
value = np.array(value, dtype=np.float32)
if value.ndim != 2 or value.shape[1] != 2:
raise ValueError('`poss` must be an n by 2 array')
super().__setattr__(name, value)
if not hasattr(self, '_initialized') or not self._initialized: return
if name != '_uProps' and hasattr(self, '_uProps') and \
name in self._uProps:
self._prog.setUniform(*self._uProps[name], value)
if name in {'texts', 'poss', 'fontSize', 'bold', 'italic',
'align', 'bgColor', 'fgColor'}:
self.refresh()
def initializeGL(self):
self._tex = glGenTextures(1)
self._prog = Program(vert=self._vertShader, geom=self._geomShader,
frag=self._fragShader)
# properties linked with a uniform variable in the shader
self._uProps = dict(pos=('uPos', '2f'), size=('uSize', '2f'),
margin=('uMargin', '4f'), anchor=('uAnchor', '2f'),
offset=('uOffset', '2f'))
with self._prog:
for name, value in self._uProps.items():
self._prog.setUniform(*value, self._props[name])
self._prog.setUniform('uPixelRatio', '1f', getPixelRatio())
self.refresh()
super().initializeGL()
def resizeGL(self):
super().resizeGL()
with self._prog:
self._prog.setUniform('uParentPos', '2f', self.parent.posPxl)
self._prog.setUniform('uParentSize', '2f', self.parent.sizePxl)
self._prog.setUniform('uCanvasSize', '2f', self.canvas.sizePxl)
def refresh(self):
'''Generates texture for the given text, font, color, etc.
Note: This function does not force redrawing of the text on screen.
'''
if not self.texts: return
# generate a Qt font object for each text instance
ratio = getPixelRatio()
fontSizes = np.array(self.fontSize, ndmin=1) * ratio
if fontSizes.shape[0] < len(self.texts):
pad = len(self.texts) - fontSizes.shape[0]
fontSizes = np.pad(fontSizes, (0,pad), 'edge')
bold = QtGui.QFont.Bold if self.bold else QtGui.QFont.Normal
fonts = [QtGui.QFont('arial', int(fontSize), bold, self.italic)
for fontSize in fontSizes]
# calcualte size of each text instance in pixels
sizes = np.zeros((len(self.texts), 2), dtype=np.float32)
for i, text in enumerate(self.texts):
sizes[i] = Text.getSize(text, fonts[i])
sizes = sizes.clip(1) # size of 0 not allowed
# w and h of the 3D texture has be max of all text sizes
w = int(sizes[:, 0].max())
h = int(sizes[:, 1].max())
texData = np.zeros((len(self.texts), h, w, 4), dtype=np.float32)
fgColors = np.array(self.fgColor, ndmin=2)
if fgColors.shape[0] < len(self.texts):
pad = len(self.texts) - fgColors.shape[0]
fgColors = np.pad(fgColors, ((0,pad),(0,0)), 'edge')
# draw text elements
for i, text in enumerate(self.texts):
w, h = sizes[i].astype(np.int)
image = QtGui.QImage(w, h, QtGui.QImage.Format_ARGB32)
image.fill(QtGui.QColor(*np.array(self.bgColor)*255))
painter = QtGui.QPainter()
painter.begin(image)
painter.setPen(QtGui.QColor(*(fgColors[i]*255).astype(int)))
painter.setFont(fonts[i])
painter.drawText(0, 0, w, h, self.align, text)
painter.end()
str = image.bits().asstring(w * h * 4)
texData[i, :h, :w, :] = np.frombuffer(str,
dtype=np.uint8).reshape((h, w, 4))
# normalize text sizes by device pixel ratio (Qt compatible)
sizes = sizes / ratio
# ensure `poss` is at least the same length as `texts`
poss = np.array(self.poss, np.float32)
if poss.shape[0] < len(self.texts):
pad = len(self.texts) - poss.shape[0]
poss = np.pad(poss, ((0,pad), (0,0)), 'constant', constant_values=0)
with self._prog:
self._prog.setUniform('uTexSize', '3f', texData.shape[:-1])
self._prog.setVBO('aPos', GL_FLOAT, 2, poss, GL_DYNAMIC_DRAW)
self._prog.setVBO('aSize', GL_FLOAT, 2, sizes, GL_DYNAMIC_DRAW)
# texture
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_3D, self._tex)
glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, texData.shape[2],
texData.shape[1], texData.shape[0], 0, GL_BGRA, GL_UNSIGNED_BYTE,
texData)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
def paintGL(self):
if not self.visible: return
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_3D, self._tex)
with self._prog:
glDrawArrays(GL_POINTS, 0, len(self.texts))
super().paintGL()
class Rectangle(Item):
'''Graphical rectangle with border and fill.'''
_vertShader = '''
in vec2 aVertex;
uniform vec2 uPos; // unit
uniform vec2 uSize; // unit
uniform vec4 uMargin; // pixels: l t r b
uniform vec2 uParentPos; // pixels
uniform vec2 uParentSize; // pixels
uniform vec2 uCanvasSize; // pixels
void main() {
// transform inside parent
vec2 pos = (uPos * uParentSize + uParentPos) / uCanvasSize;
vec2 size = uSize * uParentSize / uCanvasSize;
// add margin
pos += uMargin.xw / uCanvasSize;
size -= (uMargin.xy + uMargin.zw) / uCanvasSize;
// apply transformation to vertex and take to NDC space
gl_Position = vec4((aVertex * size + pos) * 2 - vec2(1), 0, 1);
}
'''
_fragShader = '''
out vec4 FragColor;
uniform vec2 uPos; // unit
uniform vec2 uSize; // unit
uniform vec4 uMargin; // pixels: l t r b
uniform float uBorderWidth; // pixels
uniform vec2 uParentPos; // pixels
uniform vec2 uParentSize; // pixels
uniform vec2 uCanvasSize; // pixels
uniform float uPixelRatio;
uniform vec4 uBgColor;
uniform vec4 uFgColor;
void main() {
// high DPI display support
vec2 fragCoord = gl_FragCoord.xy / uPixelRatio;
// transform to pixel space
vec4 rect = vec4(uPos * uParentSize + uParentPos + uMargin.xw,
(uPos + uSize) * uParentSize + uParentPos - uMargin.zy).xwzy;
// check border
if (between(rect.x, fragCoord.x, rect.z) &&
(between(-uBorderWidth, fragCoord.y-rect.y, 0) ||
between(0, fragCoord.y-rect.w, uBorderWidth)) ||
between(rect.w, fragCoord.y, rect.y) &&
(between(0, fragCoord.x-rect.x, uBorderWidth) ||
between(-uBorderWidth, fragCoord.x-rect.z, 0)))
FragColor = uFgColor;
else
FragColor = uBgColor;
}
'''
def __init__(self, parent, **kwargs):
'''
'''
# properties with their default values
defaults = dict(borderWidth=1)
self._initProps(defaults, kwargs)
super().__init__(parent, **kwargs)
def __setattr__(self, name, value):
super().__setattr__(name, value)
if not hasattr(self, '_initialized') or not self._initialized: return
if name != '_uProps' and hasattr(self, '_uProps') and \
name in self._uProps:
self._prog.setUniform(*self._uProps[name], value)
def initializeGL(self):
vertices = np.array([
[0, 0],
[0, 1],
[1, 1],
[1, 0],
], dtype=np.float32)
self._indices = np.array([
[0, 1, 2],
[0, 2, 3],
], dtype=np.uint32)