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
|
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2019-2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
"""
This module provides a class to render a set of 2D triangles
"""
__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "03/04/2017"
import ctypes
import numpy
from .....math.combo import min_max
from .... import _glutils as glutils
from ...._glutils import gl
from .GLPlotItem import GLPlotItem
class GLPlotTriangles(GLPlotItem):
"""Handle rendering of a set of colored triangles"""
_PROGRAM = glutils.Program(
vertexShader="""
#version 120
uniform mat4 matrix;
attribute float xPos;
attribute float yPos;
attribute vec4 color;
varying vec4 vColor;
void main(void) {
gl_Position = matrix * vec4(xPos, yPos, 0.0, 1.0);
vColor = color;
}
""",
fragmentShader="""
#version 120
uniform float alpha;
varying vec4 vColor;
void main(void) {
gl_FragColor = vColor;
gl_FragColor.a *= alpha;
}
""",
attrib0='xPos')
def __init__(self, x, y, color, triangles, alpha=1.):
"""
:param numpy.ndarray x: X coordinates of triangle corners
:param numpy.ndarray y: Y coordinates of triangle corners
:param numpy.ndarray color: color for each point
:param numpy.ndarray triangles: (N, 3) array of indices of triangles
:param float alpha: Opacity in [0, 1]
"""
super().__init__()
# Check and convert input data
x = numpy.ravel(numpy.array(x, dtype=numpy.float32))
y = numpy.ravel(numpy.array(y, dtype=numpy.float32))
color = numpy.array(color, copy=False)
# Cast to uint32
triangles = numpy.array(triangles, copy=False, dtype=numpy.uint32)
assert x.size == y.size
assert x.size == len(color)
assert color.ndim == 2 and color.shape[1] in (3, 4)
if numpy.issubdtype(color.dtype, numpy.floating):
color = numpy.array(color, dtype=numpy.float32, copy=False)
elif numpy.issubdtype(color.dtype, numpy.integer):
color = numpy.array(color, dtype=numpy.uint8, copy=False)
else:
raise ValueError('Unsupported color type')
assert triangles.ndim == 2 and triangles.shape[1] == 3
self.__x_y_color = x, y, color
self.xMin, self.xMax = min_max(x, finite=True)
self.yMin, self.yMax = min_max(y, finite=True)
self.__triangles = triangles
self.__alpha = numpy.clip(float(alpha), 0., 1.)
self.__vbos = None
self.__indicesVbo = None
self.__picking_triangles = None
def pick(self, x, y):
"""Perform picking
:param float x: X coordinates in plot data frame
:param float y: Y coordinates in plot data frame
:return: List of picked data point indices
:rtype: Union[List[int],None]
"""
if (x < self.xMin or x > self.xMax or
y < self.yMin or y > self.yMax):
return None
xPts, yPts = self.__x_y_color[:2]
if self.__picking_triangles is None:
self.__picking_triangles = numpy.zeros(
self.__triangles.shape + (3,), dtype=numpy.float32)
self.__picking_triangles[:, :, 0] = xPts[self.__triangles]
self.__picking_triangles[:, :, 1] = yPts[self.__triangles]
segment = numpy.array(((x, y, -1), (x, y, 1)), dtype=numpy.float32)
# Picked triangle indices
indices = glutils.segmentTrianglesIntersection(
segment, self.__picking_triangles)[0]
# Point indices
indices = numpy.unique(numpy.ravel(self.__triangles[indices]))
# Sorted from furthest to closest point
dists = (xPts[indices] - x) ** 2 + (yPts[indices] - y) ** 2
indices = indices[numpy.flip(numpy.argsort(dists), axis=0)]
return tuple(indices) if len(indices) > 0 else None
def discard(self):
"""Release resources on the GPU"""
if self.__vbos is not None:
self.__vbos[0].vbo.discard()
self.__vbos = None
self.__indicesVbo.discard()
self.__indicesVbo = None
def prepare(self):
"""Allocate resources on the GPU"""
if self.__vbos is None:
self.__vbos = glutils.vertexBuffer(self.__x_y_color)
# Normalization is need for color
self.__vbos[-1].normalization = True
if self.__indicesVbo is None:
self.__indicesVbo = glutils.VertexBuffer(
numpy.ravel(self.__triangles),
usage=gl.GL_STATIC_DRAW,
target=gl.GL_ELEMENT_ARRAY_BUFFER)
def render(self, context):
"""Perform rendering
:param RenderContext context: Rendering information
"""
self.prepare()
if self.__vbos is None or self.__indicesVbo is None:
return # Nothing to display
self._PROGRAM.use()
gl.glUniformMatrix4fv(self._PROGRAM.uniforms['matrix'],
1,
gl.GL_TRUE,
context.matrix.astype(numpy.float32))
gl.glUniform1f(self._PROGRAM.uniforms['alpha'], self.__alpha)
for index, name in enumerate(('xPos', 'yPos', 'color')):
attr = self._PROGRAM.attributes[name]
gl.glEnableVertexAttribArray(attr)
self.__vbos[index].setVertexAttrib(attr)
with self.__indicesVbo:
gl.glDrawElements(gl.GL_TRIANGLES,
self.__triangles.size,
glutils.numpyToGLType(self.__triangles.dtype),
ctypes.c_void_p(0))
|