Esempio n. 1
0
    def __init__(self, workspace, surface: QSurface):
        super().__init__()

        self.surf = surface
        prof = QOpenGLVersionProfile()
        prof.setVersion(2, 0)

        self.vao = GL.glGenVertexArrays(1)
        self.vbo, self.vbo2 = GL.glGenBuffers(2)

        self.texture = -1
        self.current_model: BlockModel = None
        self.workspace = workspace

        self.array1, array2 = None, None

        self.shader = QOpenGLShaderProgram()
        self.shader.addShaderFromSourceFile(QOpenGLShader.Vertex,
                                            "shader/block.vertex.glsl")
        self.shader.addShaderFromSourceFile(QOpenGLShader.Fragment,
                                            "shader/block.fragment.glsl")
        self.shader.link()

        self.proj_mat = glm.perspective(
            1.57,
            self.surf.size().width() / self.surf.size().height(), 0.1, 100)
        self.texture = GL.glGenTextures(1)
Esempio n. 2
0
    def initializeGL(self):
        GL.glClearColor(0.15, 0.15, 0.15, 1.0)
        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glEnable(GL.GL_LIGHT0)
        GL.glEnable(GL.GL_LIGHTING)

        self.program = QOpenGLShaderProgram(self)
        self.program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                                             self.vertexShaderSource)
        self.program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                                             self.fragmentShaderSource)
        self.program.link()
        self.xRot = 0
        self.yRot = 0
        self.zRot = 0

        self.vertexAtr = self.program.attributeLocation("vertexAtr")
        self.colAttr = self.program.attributeLocation("colAttr")

        self.projectionMatrixAttr = self.program.uniformLocation(
            "projectionMatrix")
        self.modelViewMatrixAttr = self.program.uniformLocation(
            "modelViewMatrix")
        self.normalMatrixAttr = self.program.uniformLocation("normalMatrix")

        self.normalAttr = self.program.attributeLocation("normalAttr")

        self.controlPtsAttr = self.program.attributeLocation("controlPtsAttr")
        self.pressClick = QVector3D(0, 0, 0)
        self.releaseClick = QVector3D(0, 0, 0)
        self.programid = 0
Esempio n. 3
0
    def setupGL(self):

        self.program = QOpenGLShaderProgram(self.context())
        info("PROGRAM", self.program)

        # addShaderFromSourceCode() only returns a bool telling whether everything went well

        if self.program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                                                self.vertexShaderSource):
            info("VERTEX SHADER",
                 "Managed to load and parse the vertex shader")

        if self.program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                                                self.fragmentShaderSource):
            info("FRAGMENT SHADER",
                 "Managed to load and parse the fragment shader")

        # Compile and bind the shader program to the current context
        self.program.link()
        self.program.bind()

        # Tell GL that whenever we run glClear, this is the color that
        # should be used. We only need to do this once.
        self.gl.glClearColor(0.1, 0.1, 0.1, 1.0)

        self.dumpGLLogMessages("setupGL()")
Esempio n. 4
0
    def initializeGL(self):
        self.makeObject()

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)

        vshader = QOpenGLShader(QOpenGLShader.Vertex, self)
        vshader.compileSourceCode(self.vsrc)

        fshader = QOpenGLShader(QOpenGLShader.Fragment, self)
        fshader.compileSourceCode(self.fsrc)

        self.program = QOpenGLShaderProgram(self)
        self.program.addShader(vshader)
        self.program.addShader(fshader)
        self.program.bindAttributeLocation('vertex',
                                           self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.bindAttributeLocation('texCoord',
                                           self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.link()

        self.program.bind()
        self.program.setUniformValue('texture', 0)

        self.program.enableAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.enableAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.setAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE,
                                       self.vertices)
        self.program.setAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE,
                                       self.texCoords)
Esempio n. 5
0
    def initializeGL(self):

        self.resized = True

        self.output = zeros((100, 100))

        logger.debug("initializeGL")

        self.programTex = QOpenGLShaderProgram()
        self.programTex.addShaderFromSourceCode(QOpenGLShader.Vertex,
                                                vertShaderTex)
        self.programTex.addShaderFromSourceCode(QOpenGLShader.Fragment,
                                                fragShaderTex)
        self.programTex.link()
        self.programTex.bind()
        logger.debug("GLSL programTex log:%s", self.programTex.log())

        glClearColor(0, 0, 0, 1.)

        self.texture = None

        self.quadCoord = np.array([[-1., -1., 0.], [1., -1., 0.], [1., 1., 0.],
                                   [1., 1., 0.], [-1., 1., 0.], [-1., -1.,
                                                                 0.]])

        self.quadCoordTex = np.array([[0, 0], [1., 0.], [1., 1.], [1., 1.],
                                      [0, 1.], [0, 0]])

        self.set_colormap(spimagine.config.__DEFAULTCOLORMAP__)

        glDisable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
Esempio n. 6
0
    def initializeGL(self):
        version_profile = QOpenGLVersionProfile()
        version_profile.setVersion(2, 0)
        self.gl = self.context().versionFunctions(version_profile)
        self.gl.initializeOpenGLFunctions()

        self.makeObject()

        self.gl.glEnable(self.gl.GL_DEPTH_TEST)
        self.gl.glEnable(self.gl.GL_CULL_FACE)

        vshader = QOpenGLShader(QOpenGLShader.Vertex, self)
        vshader.compileSourceCode(self.vsrc)

        fshader = QOpenGLShader(QOpenGLShader.Fragment, self)
        fshader.compileSourceCode(self.fsrc)

        self.program = QOpenGLShaderProgram()
        self.program.addShader(vshader)
        self.program.addShader(fshader)
        self.program.bindAttributeLocation("vertex",
                                           self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.bindAttributeLocation("texCoord",
                                           self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.link()

        self.program.bind()
        self.program.setUniformValue("texture", 0)

        self.program.enableAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.enableAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.setAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE,
                                       self.vertices)
        self.program.setAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE,
                                       self.texCoords)
    def paint(self):
        # for Darwin, it's a must
        if pf.uname().system == 'Darwin':
            global GL
            GL = self._window.openglContext().versionFunctions()

        w = self._viewport_size.width()
        h = self._viewport_size.height()

        GL.glViewport(0, 0, int(w), int(h))

        if self._shader_program is None:
            self._shader_program = QOpenGLShaderProgram()
            self._shader_program.addShaderFromSourceFile(
                QOpenGLShader.Vertex, 'shaders/OpenGL_2_1/vertex.glsl')
            self._shader_program.addShaderFromSourceFile(
                QOpenGLShader.Fragment, 'shaders/OpenGL_2_1/fragment.glsl')
            self._shader_program.bindAttributeLocation('position', 0)
            self._shader_program.bindAttributeLocation('color', 1)
            self._shader_program.link()

        self._shader_program.bind()
        self._shader_program.enableAttributeArray(0)
        self._shader_program.enableAttributeArray(1)

        self._shader_program.setAttributeArray(0, positions)
        self._shader_program.setAttributeArray(1, colors)

        if self._projection_type == 0:
            self._projection_matrix = self._perspective_projection_matrix
        elif self._projection_type == 1:
            self._projection_matrix = self._orthographic_projection_matrix

        self._model_matrix = self.build_rotation_matrix()

        self._shader_program.setUniformValue(
            'model_matrix', QMatrix4x4(self._model_matrix.flatten().tolist()))

        self._shader_program.setUniformValue(
            'view_matrix',
            QMatrix4x4(self._camera.get_view_matrix().flatten().tolist()))

        self._shader_program.setUniformValue(
            'projection_matrix',
            QMatrix4x4(self._projection_matrix.flatten().tolist()))

        GL.glClearColor(0.2, 0.2, 0.2, 1)
        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)

        self._shader_program.disableAttributeArray(0)
        self._shader_program.disableAttributeArray(1)

        self._shader_program.release()

        # Restore the OpenGL state for QtQuick rendering
        self._window.resetOpenGLState()
        self._window.update()
Esempio n. 8
0
    def setVertexShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(
                QOpenGLShader.Vertex, shader):
            Logger.log("e", "Vertex shader failed to compile: %s",
                       self._shader_program.log())
Esempio n. 9
0
 def _shader_from_file(self, fname_vert, fname_frag):
     shader = QOpenGLShaderProgram()
     shader.addShaderFromSourceFile(QOpenGLShader.Vertex, fname_vert)
     shader.addShaderFromSourceFile(QOpenGLShader.Fragment, fname_frag)
     shader.link()
     shader.bind()
     logger.debug("GLSL program log:%s", shader.log())
     return shader
Esempio n. 10
0
    def setGeometryShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(
                QOpenGLShader.Geometry, shader):
            Logger.log("e", "Geometry shader failed to compile: %s",
                       self._shader_program.log())
Esempio n. 11
0
    def setFragmentShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(
                QOpenGLShader.Fragment, shader):
            Logger.log("e", "Fragment shader failed to compile: %s",
                       self._shader_program.log())
Esempio n. 12
0
    def setGeometryShader(self, shader: str) -> bool:
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not cast(QOpenGLShaderProgram, self._shader_program).addShaderFromSourceCode(QOpenGLShader.Geometry, shader):
            Logger.log("e", "Geometry shader failed to compile: %s", self._shader_program.log())
            return False

        return True
Esempio n. 13
0
 def initializeGL(self):
     qDebug("initializeGL()")
     if self.logger:
         self.logger.initialize()
         self.logger.messageLogged.connect(lambda message: qDebug(self.__tr("OpenGL debug message: {0}").fomat(message.message())))
         self.logger.startLogging()
     
     gl = QOpenGLContext.currentContext().versionFunctions(glVersionProfile)
     QOpenGLContext.currentContext().aboutToBeDestroyed.connect(self.cleanup)
     
     self.clean = False
     
     fragmentShader = None
     vertexShader = vertexShader2D
     if self.ddsFile.isCubemap:
         fragmentShader = fragmentShaderCube
         vertexShader = vertexShaderCube
         if QOpenGLContext.currentContext().hasExtension(b"GL_ARB_seamless_cube_map"):
             GL_TEXTURE_CUBE_MAP_SEAMLESS = 0x884F
             gl.glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)
     elif self.ddsFile.glFormat.samplerType == "F":
         fragmentShader = fragmentShaderFloat
     elif self.ddsFile.glFormat.samplerType == "UI":
         fragmentShader = fragmentShaderUInt
     else:
         fragmentShader = fragmentShaderSInt
     
     self.program = QOpenGLShaderProgram(self)
     self.program.addShaderFromSourceCode(QOpenGLShader.Vertex, vertexShader)
     self.program.addShaderFromSourceCode(QOpenGLShader.Fragment, fragmentShader)
     self.program.bindAttributeLocation("position", 0)
     self.program.bindAttributeLocation("texCoordIn", 1)
     self.program.link()
     
     self.transparecyProgram = QOpenGLShaderProgram(self)
     self.transparecyProgram.addShaderFromSourceCode(QOpenGLShader.Vertex, transparencyVS)
     self.transparecyProgram.addShaderFromSourceCode(QOpenGLShader.Fragment, transparencyFS)
     self.transparecyProgram.bindAttributeLocation("position", 0)
     self.transparecyProgram.link()
     
     self.vao = QOpenGLVertexArrayObject(self)
     vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao)
     
     self.vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)
     self.vbo.create()
     self.vbo.bind()
     
     theBytes = struct.pack("%sf" % len(vertices), *vertices)
     self.vbo.allocate(theBytes, len(theBytes))
     
     gl.glEnableVertexAttribArray(0)
     gl.glEnableVertexAttribArray(1)
     gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, False, 6 * 4, 0)
     gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, False, 6 * 4, 4 * 4)
     
     self.texture = self.ddsFile.asQOpenGLTexture(gl, QOpenGLContext.currentContext())
Esempio n. 14
0
    def paint(self):
        if not self.m_program:
            self.gl.initializeOpenGLFunctions()

            self.m_program = QOpenGLShaderProgram(self)
            self.m_program.addShaderFromSourceCode(
                QOpenGLShader.Vertex, "attribute highp vec4 vertices;"
                "varying highp vec2 coords;"
                "void main() {"
                "    gl_Position = vertices;"
                "    coords = vertices.xy;"
                "}")
            self.m_program.addShaderFromSourceCode(
                QOpenGLShader.Fragment, "uniform lowp float t;"
                "varying highp vec2 coords;"
                "void main() {"
                "    lowp float i = 1. - (pow(abs(coords.x), 4.) + pow(abs(coords.y), 4.));"
                "    i = smoothstep(t - 0.8, t + 0.8, i);"
                "    i = floor(i * 20.) / 20.;"
                "    gl_FragColor = vec4(coords * .5 + .5, i, i);"
                "}")

            self.m_program.bindAttributeLocation("vertices", 0)

            self.m_program.link()

        self.m_program.bind()

        self.m_program.enableAttributeArray(0)

        values = [(-1, -1), (1, -1), (-1, 1), (1, 1)]

        self.m_program.setAttributeArray(0, values)

        self.m_program.setUniformValue("t", self.m_t)

        #print("DATA:",self.m_viewportSize.width(), self.m_viewportSize.height(), self.m_t)#, self.gl.glViewport)

        self.gl.glViewport(0, 0, self.m_viewportSize.width(),
                           self.m_viewportSize.height())

        self.gl.glDisable(self.gl.GL_DEPTH_TEST)

        self.gl.glClearColor(0, 0, 0, 1)

        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT)

        self.gl.glEnable(self.gl.GL_BLEND)

        self.gl.glBlendFunc(self.gl.GL_SRC_ALPHA, self.gl.GL_ONE)

        self.gl.glDrawArrays(self.gl.GL_TRIANGLE_STRIP, 0, 4)

        self.m_program.disableAttributeArray(0)

        self.m_program.release()
Esempio n. 15
0
    def setFragmentShader(self, shader):
        """Set the fragment shader to use.

        :param shader: :type{string} The fragment shader to use.
        """
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Fragment, shader):
            Logger.log("e", "Fragment shader failed to compile: %s", self._shader_program.log())
Esempio n. 16
0
    def __init__(self, processor, df, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.processor = processor
        # Data
        self.df = df

        # UI
        self.setupUi(self)
        self.setupControls()
        self.keyPressEvent = self.keyPressed
        self.mouseMoveEvent = self.mouseMoved

        # Control & Display
        self.mouse_grabbed = False

        self.camera_pos = QVector3D(0.5, 0.5, -2)  # Start camera position
        self.center = QVector3D(0.5, 0, 0.5)  # Center of object
        self.rot_center = QVector3D(0.5, 0.5, 0.5)  # Center of rotation
        self.camera_rot = QVector3D(0, 0, 1)  # Camera rotation
        self.scale_vec = QVector3D(1, 1, 1)  # Object scale
        self.real_prop = processor.get_real_scaling()  # val to lat

        self.light_pos = QVector3D(self.xLightSpinBox.value(),
                                   self.yLightSpinBox.value(),
                                   self.zLightSpinBox.value())
        self.ambient = self.ambientSlider.value() / 100
        self.diffuse = self.diffuseSlider.value() / 100
        self.alpha = self.alphaSlider.value() / 100  # Transparency

        # Drawing
        self.normals = []
        self.colors = []
        self.coords_array = []
        # !> len(self.normals) == len(self.colors) == len(self.coords_array)

        self.update_light = False  # Update for light is needed
        self.update_buffer = False  # Update for whole buffer is needed

        self.show_grid = self.gridCheckBox.isChecked()
        self.show_contour = self.contourCheckBox.isChecked()
        self.contour_levels = self.contourLevelSpinBox.value()
        self.show_light_lines = True
        self.grid_freq = 10

        self.grid_color = QVector4D(1, 1, 1, 1)
        self.contour_color = QVector4D(1, 1, 1, 1)
        self.light_line_color = QVector4D(1, 0.6, 0, 1)

        self.prepareScene()
        self.updateUi()

        self.shaders = QOpenGLShaderProgram()
        self.openGLWidget.initializeGL = self.initializeGL
        self.openGLWidget.paintGL = self.paintGL
Esempio n. 17
0
 def __init__(self, parent):
     super().__init__(parent)
     self.shader_program = QOpenGLShaderProgram(parent=self)
     self.inverted = False
     self.vertex_attribute_object = None
     self.vertex_data = np.array([
         0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
         0.0, 0.0, 0.0, 1.0, 0.0
     ],
                                 dtype=np.float32)
     self.vertex_position_uniform = None
Esempio n. 18
0
    def initialize(self):
        self.m_program = QOpenGLShaderProgram(self)

        self.m_program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                                               self.vertexShaderSource)
        self.m_program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                                               self.fragmentShaderSource)

        self.m_program.link()

        self.m_posAttr = self.m_program.attributeLocation('posAttr')
        self.m_colAttr = self.m_program.attributeLocation('colAttr')
        self.m_matrixUniform = self.m_program.uniformLocation('matrix')
Esempio n. 19
0
    def create_shader(self):
        self.m_program = QOpenGLShaderProgram(self)

        self.m_program.addShaderFromSourceFile(QOpenGLShader.Vertex, "shaders/chapter2.vs.glsl")
        self.m_program.addShaderFromSourceFile(QOpenGLShader.Fragment, "shaders/chapter2.fs.glsl")

        self.m_program.link()

        self.m_vertex = self.m_program.attributeLocation("m_vertex")
        self.m_offset = self.m_program.attributeLocation("m_offset")
        self.m_color = self.m_program.attributeLocation("m_color")

        return self
Esempio n. 20
0
    def setVertexShader(self, shader: str) -> bool:
        """Set the vertex shader to use.

        :param shader: :type{string} The vertex shader to use.
        """
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not cast(QOpenGLShaderProgram, self._shader_program).addShaderFromSourceCode(QOpenGLShader.Vertex, shader):
            Logger.log("e", "Vertex shader failed to compile: %s", self._shader_program.log())
            return False

        return True
Esempio n. 21
0
 def __init__(self, context, numAttibutesInvbo=1):
     super(GLProgram, self).__init__()
     self._fakeTimer = 0
     self.num_of_elements_in_vbo = numAttibutesInvbo
     self.vertex_elements = 3
     self._program = QOpenGLShaderProgram(context)
     self._textures = []
     self._images = []
     self._vertexBufferObject = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)
     self._indexesBufferObject = QOpenGLBuffer(QOpenGLBuffer.IndexBuffer)
     self._vertexArrayObject = QOpenGLVertexArrayObject()
     self._vertices = []
     self._indices = []
     self.attributes = []
Esempio n. 22
0
    def init_shaders(self):
        program = QOpenGLShaderProgram(self)
        if not program.addShaderFromSourceFile(QOpenGLShader.Vertex, get_resources_path("shader.vert")):
            return None

        if not program.addShaderFromSourceFile(QOpenGLShader.Fragment, get_resources_path("shader.frag")):
            return None

        if not program.link():
            return None

        if not program.bind():
            return None

        return program
Esempio n. 23
0
    def _update(self):

        if self._linkDirty:
            self._program = QOpenGLShaderProgram()
            if self._vertexShader is not None:
                self._program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                                                      self._vertexShader)
            if self._geometryShader is not None:
                self._program.addShaderFromSourceCode(QOpenGLShader.Geometry,
                                                      self._geometryShader)
            if self._fragmentShader is not None:
                self._program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                                                      self._fragmentShader)
            self._program.link()
            self._linkDirty = False
Esempio n. 24
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.shader_program = QOpenGLShaderProgram()
     width = 1
     half_width = width / 2
     rect = QRectF(-half_width, -half_width, width, width)
     self.setRect(rect)
     self.vertex_attribute_object = None
     self.vertex_data = np.array([
         -half_width, -half_width, 0.0, -half_width + width, -half_width,
         0.0, -half_width + width, -half_width + width, 0.0,
         -half_width + width, -half_width + width, 0.0, -half_width,
         half_width, 0.0, -half_width, -half_width, 0.0
     ],
                                 dtype=np.float32)
     self.vertex_position_uniform = None
Esempio n. 25
0
    def initializeGL(self):
        self.gl = self.context().versionFunctions()
        self.gl.initializeOpenGLFunctions()

        self.makeObject()

        self.gl.glEnable(self.gl.GL_DEPTH_TEST)
        self.gl.glEnable(self.gl.GL_CULL_FACE)

        vshader = QOpenGLShader(QOpenGLShader.Vertex, self)
        vshader.compileSourceCode(self.vsrc)

        fshader = QOpenGLShader(QOpenGLShader.Fragment, self)
        fshader.compileSourceCode(self.fsrc)

        self.program = QOpenGLShaderProgram()
        self.program.addShader(vshader)
        self.program.addShader(fshader)
        self.program.bindAttributeLocation('vertex',
                self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.bindAttributeLocation('texCoord',
                self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.link()

        self.program.bind()
        self.program.setUniformValue('texture', 0)

        self.program.enableAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.enableAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.setAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE,
                self.vertices)
        self.program.setAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE,
                self.texCoords)
Esempio n. 26
0
    def initializeGL(self):
        GL.glClearColor(1.0, 0.0, 0.0, 1.0)
        GL.glEnable(GL.GL_BLEND)
        GL.glBlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)

        print("OpenGL.GL: " + str(GL.glGetString(GL.GL_VERSION)))
        print("GL.GLSL: " + str(GL.glGetString(GL.GL_SHADING_LANGUAGE_VERSION)))
        print("OpenGL ATTRIBUTES:\n",", ".join(d for d in dir(GL) if d.startswith("GL_")))

        self.program = QOpenGLShaderProgram()
        self.program.addShaderFromSourceCode(QOpenGLShader.Vertex, """#version 120
        attribute vec2 position;
        attribute vec2 texcoord;
        varying vec2 mytexcoord;
        void main() {
            gl_Position = vec4(position, 0., 1.0);
            mytexcoord = texcoord;
        }""")

        self.program.addShaderFromSourceCode(QOpenGLShader.Fragment, """#version 120
        uniform sampler2D texture;
        varying vec2 mytexcoord;
        void main() {
            
            gl_FragColor = texture2D(texture,mytexcoord);
        }""")
        print(self.program.log())
        self.program.link()

        self.texture = fillTexture2d(np.outer(np.linspace(0, 1, 128), np.ones(128)))
Esempio n. 27
0
    def paint(self):
        if not self.m_program:
            self.gl.initializeOpenGLFunctions()

            self.m_program = QOpenGLShaderProgram(self)
            self.m_program.addShaderFromSourceCode(
                QOpenGLShader.Vertex,
                "attribute highp vec4 vertices;"
                "varying highp vec2 coords;"
                "void main() {"
                "    gl_Position = vertices;"
                "    coords = vertices.xy;"
                "}",
            )
            self.m_program.addShaderFromSourceCode(
                QOpenGLShader.Fragment,
                "uniform lowp float t;"
                "varying highp vec2 coords;"
                "void main() {"
                "    lowp float i = 1. - (pow(abs(coords.x), 4.) + pow(abs(coords.y), 4.));"
                "    i = smoothstep(t - 0.8, t + 0.8, i);"
                "    i = floor(i * 20.) / 20.;"
                "    gl_FragColor = vec4(coords * .5 + .5, i, i);"
                "}",
            )

            self.m_program.bindAttributeLocation("vertices", 0)

            self.m_program.link()

        self.m_program.bind()

        self.m_program.enableAttributeArray(0)

        values = [(-1, -1), (1, -1), (-1, 1), (1, 1)]

        self.m_program.setAttributeArray(0, values)

        self.m_program.setUniformValue("t", self.m_t)

        # print("DATA:",self.m_viewportSize.width(), self.m_viewportSize.height(), self.m_t)#, self.gl.glViewport)

        self.gl.glViewport(0, 0, self.m_viewportSize.width(), self.m_viewportSize.height())

        self.gl.glDisable(self.gl.GL_DEPTH_TEST)

        self.gl.glClearColor(0, 0, 0, 1)

        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT)

        self.gl.glEnable(self.gl.GL_BLEND)

        self.gl.glBlendFunc(self.gl.GL_SRC_ALPHA, self.gl.GL_ONE)

        self.gl.glDrawArrays(self.gl.GL_TRIANGLE_STRIP, 0, 4)

        self.m_program.disableAttributeArray(0)

        self.m_program.release()
Esempio n. 28
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.scene_shader_program = QOpenGLShaderProgram()
        self.screen_shader_program = QOpenGLShaderProgram()
        x0 = -0.5
        y0 = -0.5
        width = 1

        self.vertex_data = np.array([
            x0, y0, 0.0,
            x0 + width, y0, 0.0,
            x0 + width, y0 + width, 0.0,

            x0 + width, y0 + width, 0.0,
            x0, y0 + width, 0.0,
            x0, y0, 0.0,
        ], dtype=np.float32)
Esempio n. 29
0
    def __init__(self, homography_transform, parent=None):
        super().__init__(parent)
        self._background_colour = None
        self._drawables = []
        self._image = None
        self._intensity_mask = None
        self.centre_x_uniform = None
        self.centre_y_uniform = None
        self.crosshair = Crosshair(self)
        self.height_uniform = None
        self.image_to_upload = None
        self.gl_initialised = False
        self.shape_uniform = None
        self.max_height_uniform = None
        self.rotation_uniform = None
        self.texture = -1
        self.texture_uploaded = False
        self.width_x_uniform = None
        self.width_y_uniform = None
        self.homography_transform = homography_transform
        self.projection_matrix = QMatrix4x4()
        self.view_matrix = QMatrix4x4()
        self.set_background_colour(0)
        self.shader_program = QOpenGLShaderProgram()
        self._show_crosshair = False
        self._show_scale_bar = False
        self._crosshair_thickness = 1
        self._gaussian_shape = QVector2D()
        self._image_to_render = None
        self._inverted = False
        self._scale_bar_thickness = 1
        self._scale_bar_width = 10
        self._use_homography = False
        self._use_intensity_mask = False

        self.gaussian = Gaussian()

        self.transform = QTransform()
        self.dx = 0
        self.dy = 0
        self.rotation = 0
        self.scale_value = 1

        self.setWindowTitle('Stimulus Window')

        self.homography_transform.matrixChanged.connect(self.update_image)
Esempio n. 30
0
 def __init__(self):
     self.invert = None
     self.shader_program = QOpenGLShaderProgram()
     self.vertex_attribute_object = None
     self.vertex_position = None
     self.projection = QMatrix4x4()
     self.model = QMatrix4x4()
     self.view = QMatrix4x4()
Esempio n. 31
0
class GLSLProgram(Product.Product):
    def __init__(self,
                 parent=None,
                 vertex_shader=None,
                 geometry_shader=None,
                 fragment_shader=None,
                 uniforms={},
                 textures={},
                 outputTextures={}):
        super(GLSLProgram, self).__init__(parent)
        self._vertexShader = None
        self._geometryShader = None
        self._fragmentShader = None
        self._uniforms = {}
        self._textures = {}
        self._outputTextures = {}
        self._linkDirty = False

        self.vertexShader = vertex_shader
        self.geometryShader = geometry_shader
        self.fragmentShader = fragment_shader
        self.uniforms = uniforms
        self.textures = textures
        self.outputTextures = outputTextures

    def _update(self):

        if self._linkDirty:
            self._program = QOpenGLShaderProgram()
            if self._vertexShader is not None:
                self._program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                                                      self._vertexShader)
            if self._geometryShader is not None:
                self._program.addShaderFromSourceCode(QOpenGLShader.Geometry,
                                                      self._geometryShader)
            if self._fragmentShader is not None:
                self._program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                                                      self._fragmentShader)
            self._program.link()
            self._linkDirty = False

    Product.InputProperty(vars(), 'QVariant', 'uniforms')
    ''' supports dict of Array, subject to the constraints associated with Image.to_QImage() '''
    Product.InputProperty(vars(), 'QVariant', 'textures')

    Product.InputProperty(vars(), 'QVariant', 'outputTextures')

    def relink(self):
        self._linkDirty = True

    Product.InputProperty(vars(), str, 'geometryShader', relink)

    Product.InputProperty(vars(), str, 'vertexShader', relink)

    Product.InputProperty(vars(), str, 'fragmentShader', relink)
Esempio n. 32
0
    def __init__(self, parent):
        super().__init__(parent)
        self.shader_program = QOpenGLShaderProgram(self)
        self.vertex_data = np.array([
            # X,    Y,   Z     U,   V
            -LOC, LOC, 0.0, 0.0, 1.0,
            LOC, LOC, 0.0, 1.0, 1.0,
            LOC, -LOC, 0.0, 1.0, 0.0,

            LOC, -LOC, 0.0, 1.0, 0.0,
            -LOC, -LOC, 0.0, 0.0, 0.0,
            -LOC, LOC, 0.0, 0.0, 1.0,
        ], dtype=np.float32)

        self._image = None#QImage()
        self.vao = None
        self.vertex_position_uniform = -1
        self.
Esempio n. 33
0
    def __init__(self):
        self.initialised = False
        self.shader_program = QOpenGLShaderProgram()
        self.vertex_position = None
        self.texture = 0
        self.frame_buffer = 0
        self.recreate_frame_buffer = True

        x0 = -1
        y0 = -1
        width = 2

        self.vertex_data = np.array([
            x0, y0, 0.0, 0.0, 0.0, x0 + width, y0, 0.0, 1.0, 0.0, x0 + width,
            y0 + width, 0.0, 1.0, 1.0, x0 + width, y0 + width, 0.0, 1.0, 1.0,
            x0, y0 + width, 0.0, 0.0, 1.0, x0, y0, 0.0, 0.0, 0.0
        ],
                                    dtype=np.float32)
Esempio n. 34
0
    def __init__(self):
        super(LogoRenderer, self).__init__()
        self.m_fAngle = None
        self.m_fScale = None
        self.vertices = []
        self.normals = []
        self.program1 = QOpenGLShaderProgram()
        self.vertexAttr1 = 0
        self.normalAttr1 = 0
        self.matrixUniform1 = 0

        ver = QOpenGLVersionProfile()
        ver.setVersion(2, 1)
        cntx = QOpenGLContext.currentContext()
        #print("QOpenGLContext:", cntx, ver)
        fmt = cntx.format()
        fmt.setVersion(2, 1)
        cntx.setFormat(fmt)
        self.gl = cntx.versionFunctions(ver)
Esempio n. 35
0
class TestCanvas(Canvas):

    def __init__(self):

        with open("vertex.glsl","r") as f:
            self.vertexShaderSource = f.read()

        with open("fragment.glsl","r") as f:
            self.fragmentShaderSource = f.read()

        if self.vertexShaderSource is None:
            raise Exception("Could not load the source for the vertex shader")

        if self.fragmentShaderSource is None:
            raise Exception("Could not load the source for the fragment shader")

        super(TestCanvas,self).__init__()

    def setupGL(self):

        self.program = QOpenGLShaderProgram(self.context())
        info("PROGRAM",self.program)

        # addShaderFromSourceCode() only returns a bool telling whether everything went well

        if self.program.addShaderFromSourceCode(QOpenGLShader.Vertex, self.vertexShaderSource):
            info("VERTEX SHADER","Managed to load and parse the vertex shader")

        if self.program.addShaderFromSourceCode(QOpenGLShader.Fragment, self.fragmentShaderSource):
            info("FRAGMENT SHADER","Managed to load and parse the fragment shader")

        # Compile and bind the shader program to the current context
        self.program.link()
        self.program.bind()

        # Bind the shader attribute to a python variable
        self.somePosition = self.gl.glGetAttribLocation(self.program.programId(), "somePosition")

        # Tell GL that whenever we run glClear, this is the color that
        # should be used. We only need to do this once. 
        self.gl.glClearColor(0.1, 0.1, 0.1, 1.0)

        self.dumpGLLogMessages("setupGL()")

    def paintGL(self):
        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT | self.gl.GL_DEPTH_BUFFER_BIT)
        
        # Assign a value to the shader parameter
        self.gl.glVertexAttrib3f(self.somePosition, 0.5, 0.5, 0.0)

        # Mode, starting at vertex number, number of vertices to draw
        self.gl.glDrawArrays(self.gl.GL_POINTS,0,1)

        self.dumpGLLogMessages("paintGL()")

    def resizeGL(self, width, height):
        pass
Esempio n. 36
0
    def initialize(self):
        self.m_program = QOpenGLShaderProgram(self)

        self.m_program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                self.vertexShaderSource)
        self.m_program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                self.fragmentShaderSource)

        self.m_program.link()

        self.m_posAttr = self.m_program.attributeLocation('posAttr')
        self.m_colAttr = self.m_program.attributeLocation('colAttr')
        self.m_matrixUniform = self.m_program.uniformLocation('matrix')
Esempio n. 37
0
    def __init__(self):
        super(LogoRenderer, self).__init__()
        self.m_fAngle = None
        self.m_fScale = None
        self.vertices = []
        self.normals = []
        self.program1 = QOpenGLShaderProgram()
        self.vertexAttr1 = 0
        self.normalAttr1 = 0
        self.matrixUniform1 = 0

        ver = QOpenGLVersionProfile()
        ver.setVersion(2, 1)
        cntx = QOpenGLContext.currentContext()
        #print("QOpenGLContext:", cntx, ver)
        fmt = cntx.format()
        fmt.setVersion(2, 1)
        cntx.setFormat(fmt)
        self.gl = cntx.versionFunctions(ver)
Esempio n. 38
0
    def initializeGL(self):

        self.resized = True

        self.output = zeros((100, 100))

        logger.debug("initializeGL")

        self.programTex = QOpenGLShaderProgram()
        self.programTex.addShaderFromSourceCode(QOpenGLShader.Vertex, vertShaderTex)
        self.programTex.addShaderFromSourceCode(QOpenGLShader.Fragment, fragShaderTex)
        self.programTex.link()
        self.programTex.bind()
        logger.debug("GLSL programTex log:%s", self.programTex.log())

        glClearColor(0, 0, 0, 1.)

        self.texture = None

        self.quadCoord = np.array([[-1., -1., 0.],
                                   [1., -1., 0.],
                                   [1., 1., 0.],
                                   [1., 1., 0.],
                                   [-1., 1., 0.],
                                   [-1., -1., 0.]])

        self.quadCoordTex = np.array([[0, 0],
                                      [1., 0.],
                                      [1., 1.],
                                      [1., 1.],
                                      [0, 1.],
                                      [0, 0]])

        self.set_colormap(spimagine.config.__DEFAULTCOLORMAP__)

        glDisable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    def linkProgram(self, gl, name, **kwargs):
        ''' Links GLSL program from *name*.vert and *name*.frag shaders '''
        program = QOpenGLShaderProgram()

        vertexShader, fragmentShader = self.loadShaders(name)
        program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                vertexShader)
        program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                fragmentShader)

        assert program.link(), "Can't link ShaderProgram"
        assert program.bind(), "Can't bind ShaderProgram for initialization"

        for k, v in kwargs.items():
            if type(v) in [list, tuple]:
                program.setUniformValue(k, *v)
            else:
                program.setUniformValue(k, v)

        program.release()

        return program
Esempio n. 40
0
class QtShaderProgram(ShaderProgram):
    def __init__(self):
        super().__init__()

        self._shader_program = None
        self._uniform_indices = {}
        self._attribute_indices = {}
        self._uniform_values = {}
        self._bound = False
        self._textures = {}

    def setVertexShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Vertex, shader):
            Logger.log("e", "Vertex shader failed to compile: %s", self._shader_program.log())

    def setFragmentShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Fragment, shader):
            Logger.log("e", "Fragment shader failed to compile: %s", self._shader_program.log())

    def build(self):
        if not self._shader_program:
            Logger.log("e", "No shader sources loaded")
            return

        if not self._shader_program.link():
            Logger.log("e", "Shader failed to link: %s", self._shader_program.log())

    def setUniformValue(self, name, value, **kwargs):
        if not self._shader_program:
            return

        if name not in self._uniform_indices:
            self._uniform_indices[name] = self._shader_program.uniformLocation(name)

        uniform = self._uniform_indices[name]
        if uniform == -1:
            return

        if kwargs.get("cache", True):
            self._uniform_values[uniform] = value

        if self._bound:
            self._setUniformValueDirect(uniform, value)

    def setTexture(self, texture_unit, texture):
        if texture is None:
            if texture_unit in self._textures:
                del self._textures[texture_unit]
        else:
            self._textures[texture_unit] = texture

    def enableAttribute(self, name, type, offset, stride = 0):
        if not self._shader_program:
            return

        self.bind()

        if name not in self._attribute_indices:
            self._attribute_indices[name] = self._shader_program.attributeLocation(name)

        attribute = self._attribute_indices[name]
        if attribute == -1:
            return

        if type is "int":
            self._shader_program.setAttributeBuffer(attribute, 0x1404, offset, 1, stride) #GL_INT
        elif type is "float":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 1, stride) #GL_FLOAT
        elif type is "vector2f":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 2, stride) #GL_FLOAT
        elif type is "vector3f":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 3, stride) #GL_FLOAT
        elif type is "vector4f":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 4, stride) #GL_FLOAT

        self._shader_program.enableAttributeArray(attribute)


    def disableAttribute(self, name):
        if not self._shader_program:
            return

        if name not in self._attribute_indices:
            return

        self._shader_program.disableAttributeArray(self._attribute_indices[name])

    def bind(self):
        if not self._shader_program or not self._shader_program.isLinked():
            return

        if self._bound:
            return

        self._bound = True
        self._shader_program.bind()

        for uniform in self._uniform_values:
            self._setUniformValueDirect(uniform, self._uniform_values[uniform])

        for texture_unit, texture in self._textures.items():
            texture.bind(texture_unit)

    def release(self):
        if not self._shader_program or not self._bound:
            return

        self._bound = False
        self._shader_program.release()

        for texture_unit, texture in self._textures.items():
            texture.release(texture_unit)

    def _matrixToQMatrix4x4(self, m):
        return QMatrix4x4(m.at(0,0), m.at(0, 1), m.at(0, 2), m.at(0, 3),
                          m.at(1,0), m.at(1, 1), m.at(1, 2), m.at(1, 3),
                          m.at(2,0), m.at(2, 1), m.at(2, 2), m.at(2, 3),
                          m.at(3,0), m.at(3, 1), m.at(3, 2), m.at(3, 3))

    def _setUniformValueDirect(self, uniform, value):
        if type(value) is Vector:
            self._shader_program.setUniformValue(uniform, QVector3D(value.x, value.y, value.z))
        elif type(value) is Matrix:
            self._shader_program.setUniformValue(uniform, self._matrixToQMatrix4x4(value))
        elif type(value) is Color:
            self._shader_program.setUniformValue(uniform, QColor(value.r * 255, value.g * 255, value.b * 255, value.a * 255))
        elif type(value) is list and len(value) is 2:
            self._shader_program.setUniformValue(uniform, QVector2D(value[0], value[1]))
        elif type(value) is list and len(value) is 3:
            self._shader_program.setUniformValue(uniform, QVector3D(value[0], value[1], value[2]))
        elif type(value) is list and len(value) is 4:
            self._shader_program.setUniformValue(uniform, QVector4D(value[0], value[1], value[2], value[3]))
        elif type(value) is list and type(value[0]) is list and len(value[0]) is 2:
            self._shader_program.setUniformValueArray(uniform, [QVector2D(i[0], i[1]) for i in value])
        else:
            self._shader_program.setUniformValue(uniform, value)
Esempio n. 41
0
    def setVertexShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Vertex, shader):
            Logger.log("e", "Vertex shader failed to compile: %s", self._shader_program.log())
Esempio n. 42
0
class GLWidget(QOpenGLWidget):

    clicked = pyqtSignal()

    PROGRAM_VERTEX_ATTRIBUTE, PROGRAM_TEXCOORD_ATTRIBUTE = range(2)

    vsrc = """
attribute highp vec4 vertex;
attribute mediump vec4 texCoord;
varying mediump vec4 texc;
uniform mediump mat4 matrix;
void main(void)
{
    gl_Position = matrix * vertex;
    texc = texCoord;
}
"""

    fsrc = """
uniform sampler2D texture;
varying mediump vec4 texc;
void main(void)
{
    gl_FragColor = texture2D(texture, texc.st);
}
"""

    coords = (
        (( +1, -1, -1 ), ( -1, -1, -1 ), ( -1, +1, -1 ), ( +1, +1, -1 )),
        (( +1, +1, -1 ), ( -1, +1, -1 ), ( -1, +1, +1 ), ( +1, +1, +1 )),
        (( +1, -1, +1 ), ( +1, -1, -1 ), ( +1, +1, -1 ), ( +1, +1, +1 )),
        (( -1, -1, -1 ), ( -1, -1, +1 ), ( -1, +1, +1 ), ( -1, +1, -1 )),
        (( +1, -1, +1 ), ( -1, -1, +1 ), ( -1, -1, -1 ), ( +1, -1, -1 )),
        (( -1, -1, +1 ), ( +1, -1, +1 ), ( +1, +1, +1 ), ( -1, +1, +1 ))
    )

    def __init__(self, parent=None):
        super(GLWidget, self).__init__(parent)

        self.clearColor = QColor(Qt.black)
        self.xRot = 0
        self.yRot = 0
        self.zRot = 0
        self.program = None

        self.lastPos = QPoint()

    def minimumSizeHint(self):
        return QSize(50, 50)

    def sizeHint(self):
        return QSize(200, 200)

    def rotateBy(self, xAngle, yAngle, zAngle):
        self.xRot += xAngle
        self.yRot += yAngle
        self.zRot += zAngle
        self.update()

    def setClearColor(self, color):
        self.clearColor = color
        self.update()

    def initializeGL(self):
        self.gl = self.context().versionFunctions()
        self.gl.initializeOpenGLFunctions()

        self.makeObject()

        self.gl.glEnable(self.gl.GL_DEPTH_TEST)
        self.gl.glEnable(self.gl.GL_CULL_FACE)

        vshader = QOpenGLShader(QOpenGLShader.Vertex, self)
        vshader.compileSourceCode(self.vsrc)

        fshader = QOpenGLShader(QOpenGLShader.Fragment, self)
        fshader.compileSourceCode(self.fsrc)

        self.program = QOpenGLShaderProgram()
        self.program.addShader(vshader)
        self.program.addShader(fshader)
        self.program.bindAttributeLocation('vertex',
                self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.bindAttributeLocation('texCoord',
                self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.link()

        self.program.bind()
        self.program.setUniformValue('texture', 0)

        self.program.enableAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE)
        self.program.enableAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE)
        self.program.setAttributeArray(self.PROGRAM_VERTEX_ATTRIBUTE,
                self.vertices)
        self.program.setAttributeArray(self.PROGRAM_TEXCOORD_ATTRIBUTE,
                self.texCoords)

    def paintGL(self):
        self.gl.glClearColor(self.clearColor.redF(), self.clearColor.greenF(),
                self.clearColor.blueF(), self.clearColor.alphaF())
        self.gl.glClear(
                self.gl.GL_COLOR_BUFFER_BIT | self.gl.GL_DEPTH_BUFFER_BIT)

        m = QMatrix4x4()
        m.ortho(-0.5, 0.5, 0.5, -0.5, 4.0, 15.0)
        m.translate(0.0, 0.0, -10.0)
        m.rotate(self.xRot / 16.0, 1.0, 0.0, 0.0)
        m.rotate(self.yRot / 16.0, 0.0, 1.0, 0.0)
        m.rotate(self.zRot / 16.0, 0.0, 0.0, 1.0)

        self.program.setUniformValue('matrix', m)

        for i, texture in enumerate(self.textures):
            texture.bind()
            self.gl.glDrawArrays(self.gl.GL_TRIANGLE_FAN, i * 4, 4)

    def resizeGL(self, width, height):
        side = min(width, height)
        self.gl.glViewport((width - side) // 2, (height - side) // 2, side,
                side)

    def mousePressEvent(self, event):
        self.lastPos = event.pos()

    def mouseMoveEvent(self, event):
        dx = event.x() - self.lastPos.x()
        dy = event.y() - self.lastPos.y()

        if event.buttons() & Qt.LeftButton:
            self.rotateBy(8 * dy, 8 * dx, 0)
        elif event.buttons() & Qt.RightButton:
            self.rotateBy(8 * dy, 0, 8 * dx)

        self.lastPos = event.pos()

    def mouseReleaseEvent(self, event):
        self.clicked.emit()

    def makeObject(self):
        self.textures = []
        self.texCoords = []
        self.vertices = []

        root = QFileInfo(__file__).absolutePath()

        for i in range(6):
            self.textures.append(
                    QOpenGLTexture(
                            QImage(root + ('/images/side%d.png' % (i + 1))).mirrored()))

            for j in range(4):
                self.texCoords.append(((j == 0 or j == 3), (j == 0 or j == 1)))

                x, y, z = self.coords[i][j]
                self.vertices.append((0.2 * x, 0.2 * y, 0.2 * z))
Esempio n. 43
0
    def setFragmentShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Fragment, shader):
            Logger.log("e", "Fragment shader failed to compile: %s", self._shader_program.log())
Esempio n. 44
0
class TriangleWindow(OpenGLWindow):
    vertexShaderSource = '''
attribute highp vec4 posAttr;
attribute lowp vec4 colAttr;
varying lowp vec4 col;
uniform highp mat4 matrix;
void main() {
    col = colAttr;
    gl_Position = matrix * posAttr;
}
'''

    fragmentShaderSource = '''
varying lowp vec4 col;
void main() {
    gl_FragColor = col;
}
'''

    def __init__(self):
        super(TriangleWindow, self).__init__()

        self.m_program = 0
        self.m_frame = 0

        self.m_posAttr = 0
        self.m_colAttr = 0
        self.m_matrixUniform = 0

    def initialize(self):
        self.m_program = QOpenGLShaderProgram(self)

        self.m_program.addShaderFromSourceCode(QOpenGLShader.Vertex,
                self.vertexShaderSource)
        self.m_program.addShaderFromSourceCode(QOpenGLShader.Fragment,
                self.fragmentShaderSource)

        self.m_program.link()

        self.m_posAttr = self.m_program.attributeLocation('posAttr')
        self.m_colAttr = self.m_program.attributeLocation('colAttr')
        self.m_matrixUniform = self.m_program.uniformLocation('matrix')

    def render(self, gl):
        gl.glViewport(0, 0, self.width(), self.height())

        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        self.m_program.bind()

        matrix = QMatrix4x4()
        matrix.perspective(60, 4.0/3.0, 0.1, 100.0)
        matrix.translate(0, 0, -2)
        matrix.rotate(100.0 * self.m_frame / self.screen().refreshRate(),
                0, 1, 0)

        self.m_program.setUniformValue(self.m_matrixUniform, matrix)

        vertices = array.array('f', [
                 0.0,  0.707,
                -0.5, -0.5,
                 0.5, -0.5])

        gl.glVertexAttribPointer(self.m_posAttr, 2, gl.GL_FLOAT, False, 0,
                vertices)
        gl.glEnableVertexAttribArray(self.m_posAttr)

        colors = array.array('f', [
                1.0, 0.0, 0.0,
                0.0, 1.0, 0.0,
                0.0, 0.0, 1.0])

        gl.glVertexAttribPointer(self.m_colAttr, 3, gl.GL_FLOAT, False, 0,
                colors)
        gl.glEnableVertexAttribArray(self.m_colAttr)

        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)

        self.m_program.release()

        self.m_frame += 1
Esempio n. 45
0
class MyWidget(QtOpenGL.QGLWidget):
    def __init__(self, parent = None):
        super(MyWidget, self).__init__(parent)

        self.quadCoord = np.array([[-1., -1., 0.],
                                   [1., -1., 0.],
                                   [1., 1., 0.],
                                   [1., 1., 0.],
                                   [-1., 1., 0.],
                                   [-1., -1., 0.]])

        self.quadCoordTex = np.array([[0, 0],
                                      [1., 0.],
                                      [1., 1.],
                                      [1., 1.],
                                      [0, 1.],
                                      [0, 0]])

    def initializeGL(self):
        GL.glClearColor(1.0, 0.0, 0.0, 1.0)
        GL.glEnable(GL.GL_BLEND)
        GL.glBlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)

        print("OpenGL.GL: " + str(GL.glGetString(GL.GL_VERSION)))
        print("GL.GLSL: " + str(GL.glGetString(GL.GL_SHADING_LANGUAGE_VERSION)))
        print("OpenGL ATTRIBUTES:\n",", ".join(d for d in dir(GL) if d.startswith("GL_")))

        self.program = QOpenGLShaderProgram()
        self.program.addShaderFromSourceCode(QOpenGLShader.Vertex, """#version 120
        attribute vec2 position;
        attribute vec2 texcoord;
        varying vec2 mytexcoord;
        void main() {
            gl_Position = vec4(position, 0., 1.0);
            mytexcoord = texcoord;
        }""")

        self.program.addShaderFromSourceCode(QOpenGLShader.Fragment, """#version 120
        uniform sampler2D texture;
        varying vec2 mytexcoord;
        void main() {
            
            gl_FragColor = texture2D(texture,mytexcoord);
        }""")
        print(self.program.log())
        self.program.link()

        self.texture = fillTexture2d(np.outer(np.linspace(0, 1, 128), np.ones(128)))

    def paintGL(self):
        #GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        self.program.bind()

        self.program.enableAttributeArray("position")
        self.program.enableAttributeArray("texcoord")
        self.program.setAttributeArray("position", self.quadCoord)
        self.program.setAttributeArray("texcoord", self.quadCoordTex)

        GL.glActiveTexture(GL.GL_TEXTURE0)
        GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture)
        self.program.setUniformValue("texture", 0)

        GL.glDrawArrays(GL.GL_TRIANGLES, 0, len(self.quadCoord))
Esempio n. 46
0
    def loadFragmentShader(self, file):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        self._shader_program.addShaderFromSourceFile(QOpenGLShader.Fragment, file)
Esempio n. 47
0
class SquircleRenderer(QObject):  # QOpenGLFunctions
    """docstring for SquircleRenderer"""

    def __init__(self, parent=None):
        super(SquircleRenderer, self).__init__(parent)
        self.m_t = 0.0
        self.m_program = None
        self.m_viewportSize = QSize()

    def setT(self, t):
        self.m_t = t

    def setViewportSize(self, size):
        self.m_viewportSize = size

    def setWin(self, win):
        self.win = win

        ver = QOpenGLVersionProfile()
        ver.setVersion(2, 1)

        self.m_context = self.win.openglContext()
        self.gl = self.m_context.versionFunctions(ver)

    @pyqtSlot()
    def paint(self):
        if not self.m_program:
            self.gl.initializeOpenGLFunctions()

            self.m_program = QOpenGLShaderProgram(self)
            self.m_program.addShaderFromSourceCode(
                QOpenGLShader.Vertex,
                "attribute highp vec4 vertices;"
                "varying highp vec2 coords;"
                "void main() {"
                "    gl_Position = vertices;"
                "    coords = vertices.xy;"
                "}",
            )
            self.m_program.addShaderFromSourceCode(
                QOpenGLShader.Fragment,
                "uniform lowp float t;"
                "varying highp vec2 coords;"
                "void main() {"
                "    lowp float i = 1. - (pow(abs(coords.x), 4.) + pow(abs(coords.y), 4.));"
                "    i = smoothstep(t - 0.8, t + 0.8, i);"
                "    i = floor(i * 20.) / 20.;"
                "    gl_FragColor = vec4(coords * .5 + .5, i, i);"
                "}",
            )

            self.m_program.bindAttributeLocation("vertices", 0)

            self.m_program.link()

        self.m_program.bind()

        self.m_program.enableAttributeArray(0)

        values = [(-1, -1), (1, -1), (-1, 1), (1, 1)]

        self.m_program.setAttributeArray(0, values)

        self.m_program.setUniformValue("t", self.m_t)

        # print("DATA:",self.m_viewportSize.width(), self.m_viewportSize.height(), self.m_t)#, self.gl.glViewport)

        self.gl.glViewport(0, 0, self.m_viewportSize.width(), self.m_viewportSize.height())

        self.gl.glDisable(self.gl.GL_DEPTH_TEST)

        self.gl.glClearColor(0, 0, 0, 1)

        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT)

        self.gl.glEnable(self.gl.GL_BLEND)

        self.gl.glBlendFunc(self.gl.GL_SRC_ALPHA, self.gl.GL_ONE)

        self.gl.glDrawArrays(self.gl.GL_TRIANGLE_STRIP, 0, 4)

        self.m_program.disableAttributeArray(0)

        self.m_program.release()
Esempio n. 48
0
    def setGeometryShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Geometry, shader):
            Logger.log("e", "Geometry shader failed to compile: %s", self._shader_program.log())
Esempio n. 49
0
class ShaderProgram:
    def __init__(self):
        self._bindings = {}
        self._attribute_bindings = {}

        self._shader_program = None
        self._uniform_indices = {}
        self._attribute_indices = {}
        self._uniform_values = {}
        self._bound = False
        self._textures = {}

        self._debug_shader = False  # Set this to true to enable extra logging concerning shaders

    ##  Load a shader program file.
    #
    #   This method loads shaders from a simple text file, using Python's configparser
    #   as parser.
    #
    #   \note When writing shader program files, please note that configparser expects
    #   indented lines for multiline values. Since the shaders are provided as a single
    #   multiline string, make sure to indent them properly.
    #
    #   \param file_name The shader file to load.
    #   \param version can be used for a special version of the shader. it will be appended
    #          to the keys [vertex, fragment, geometry] in the shader file
    #
    #   \exception{InvalidShaderProgramError} Raised when the file provided does not contain any valid shaders.
    def load(self, file_name, version = ""):
        Logger.log("d", "Loading shader file [%s]...", file_name)

        vertex_key = "vertex" + version
        fragment_key = "fragment" + version
        geometry_key = "geometry" + version

        # Hashtags should not be ignored, they are part of GLSL.
        parser = configparser.ConfigParser(interpolation = None, comment_prefixes = (';', ))
        parser.optionxform = lambda option: option
        parser.read(file_name)

        if "shaders" not in parser:
            raise InvalidShaderProgramError("{0} is missing section [shaders]".format(file_name))

        if vertex_key not in parser["shaders"] or fragment_key not in parser["shaders"]:
            raise InvalidShaderProgramError("{0} is missing a shader [{1}, {2}]".format(file_name, vertex_key, fragment_key))

        vertex_code = parser["shaders"][vertex_key]
        if self._debug_shader:
            vertex_code_str = "\n".join(["%4i %s" % (i, s) for i, s in enumerate(vertex_code.split("\n"))])
            Logger.log("d", "Vertex shader")
            Logger.log("d", vertex_code_str)

        fragment_code = parser["shaders"][fragment_key]
        if self._debug_shader:
            fragment_code_str = "\n".join(["%4i %s" % (i, s) for i, s in enumerate(fragment_code.split("\n"))])
            Logger.log("d", "Fragment shader")
            Logger.log("d", fragment_code_str)

        self.setVertexShader(vertex_code)
        self.setFragmentShader(fragment_code)
        # Geometry shader is optional and only since version OpenGL 3.2 or with extension ARB_geometry_shader4
        if geometry_key in parser["shaders"]:
            code = parser["shaders"][geometry_key]
            if self._debug_shader:
                code_str = "\n".join(["%4i %s" % (i, s) for i, s in enumerate(code.split("\n"))])
                Logger.log("d", "Loading geometry shader... \n")
                Logger.log("d", code_str)
            self.setGeometryShader(code)

        self.build()

        if "defaults" in parser:
            for key, value in parser["defaults"].items():
                self.setUniformValue(key, ast.literal_eval(value), cache = True)

        if "bindings" in parser:
            for key, value in parser["bindings"].items():
                self.addBinding(key, value)

        if "attributes" in parser:
            for key, value in parser["attributes"].items():
                self.addAttributeBinding(key, value)

    ##  Set the vertex shader to use.
    #
    #   \param shader \type{string} The vertex shader to use.
    def setVertexShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Vertex, shader):
            Logger.log("e", "Vertex shader failed to compile: %s", self._shader_program.log())

    ##  Set the fragment shader to use.
    #
    #   \param shader \type{string} The fragment shader to use.
    def setFragmentShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Fragment, shader):
            Logger.log("e", "Fragment shader failed to compile: %s", self._shader_program.log())

    def setGeometryShader(self, shader):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        if not self._shader_program.addShaderFromSourceCode(QOpenGLShader.Geometry, shader):
            Logger.log("e", "Geometry shader failed to compile: %s", self._shader_program.log())

    ##  Build the complete shader program out of the separately provided sources.
    def build(self):
        if not self._shader_program:
            Logger.log("e", "No shader sources loaded")
            return

        if not self._shader_program.link():
            Logger.log("e", "Shader failed to link: %s", self._shader_program.log())

    ##  Set a named uniform variable.
    #
    #   Unless otherwise specified as argument, the specified value will be cached so that
    #   it does not matter whether bind() has already been called. Instead, if the shader
    #   is not currently bound, the next call to bind() will update the uniform values.
    #
    #   \param name The name of the uniform variable.
    #   \param value The value to set the variable to.
    #   \param kwargs Keyword arguments.
    #                 Possible keywords:
    #                 - cache: False when the value should not be cached for later calls to bind().
    def setUniformValue(self, name, value, **kwargs):
        if not self._shader_program:
            return

        if name not in self._uniform_indices:
            self._uniform_indices[name] = self._shader_program.uniformLocation(name)

        uniform = self._uniform_indices[name]
        if uniform == -1:
            return

        if kwargs.get("cache", True):
            self._uniform_values[uniform] = value

        if self._bound:
            self._setUniformValueDirect(uniform, value)
    ##  Set a texture that should be bound to a specified texture unit when this shader is bound.
    #
    #   \param texture_unit \type{int} The texture unit to bind the texture to.
    #   \param texture \type{Texture} The texture object to bind to the texture unit.
    def setTexture(self, texture_unit, texture):
        if texture is None:
            if texture_unit in self._textures:
                del self._textures[texture_unit]
        else:
            self._textures[texture_unit] = texture

    ##  Enable a vertex attribute to be used.
    #
    #   \param name The name of the attribute to enable.
    #   \param type The type of the attribute. Should be a python type.
    #   \param offset The offset into a bound buffer where the data for this attribute starts.
    #   \param stride The stride of the attribute.
    #
    #   \note If the shader is not bound, this will bind the shader.
    def enableAttribute(self, name, type, offset, stride = 0):
        if not self._shader_program:
            return

        self.bind()

        if name not in self._attribute_indices:
            self._attribute_indices[name] = self._shader_program.attributeLocation(name)

        attribute = self._attribute_indices[name]
        if attribute == -1:
            return

        if type is "int":
            self._shader_program.setAttributeBuffer(attribute, 0x1404, offset, 1, stride) #GL_INT
        elif type is "float":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 1, stride) #GL_FLOAT
        elif type is "vector2f":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 2, stride) #GL_FLOAT
        elif type is "vector3f":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 3, stride) #GL_FLOAT
        elif type is "vector4f":
            self._shader_program.setAttributeBuffer(attribute, 0x1406, offset, 4, stride) #GL_FLOAT

        self._shader_program.enableAttributeArray(attribute)

    ##  Disable a vertex attribute so it is no longer used.
    #
    #   \param name The name of the attribute to use.
    def disableAttribute(self, name):
        if not self._shader_program:
            return

        if name not in self._attribute_indices:
            return

        self._shader_program.disableAttributeArray(self._attribute_indices[name])

    ##  Bind the shader to use it for rendering.
    def bind(self):
        if not self._shader_program or not self._shader_program.isLinked():
            return

        if self._bound:
            return

        self._shader_program.bind()
        self._bound = True

        for uniform in self._uniform_values:
            self._setUniformValueDirect(uniform, self._uniform_values[uniform])

        for texture_unit, texture in self._textures.items():
            texture.bind(texture_unit)

    ##  Release the shader so it will no longer be used for rendering.
    def release(self):
        if not self._shader_program or not self._bound:
            return

        self._shader_program.release()
        self._bound = False

        for texture_unit, texture in self._textures.items():
            texture.release(texture_unit)

    ##  Add a uniform value binding.
    #
    #   Uniform value bindings are used to provide an abstraction between uniforms as set
    #   from code and uniforms as used from shaders. Each binding specifies a uniform name
    #   as key that should be mapped to a string that can be used to look up the value of
    #   the uniform.
    #
    #   \param key The name of the uniform to bind.
    #   \param value The string used to look up values for this uniform.
    def addBinding(self, key, value):
        self._bindings[value] = key

    ##  Remove a uniform value binding.
    #
    #   \param key The uniform to remove.
    def removeBinding(self, key):
        if key not in self._bindings:
            return

        del self._bindings[key]

    ##  Update the values of bindings.
    #
    #   \param kwargs Keyword arguments.
    #                 Each key should correspond to a binding name, with the
    #                 value being the value of the uniform.
    #
    #   \note By default, these values are not cached as they are expected to be continuously
    #         updated.
    def updateBindings(self, **kwargs):
        for key, value in kwargs.items():
            if key in self._bindings and value is not None:
                self.setUniformValue(self._bindings[key], value, cache = False)

    ##  Add an attribute binding.
    #
    #   Attribute bindings are similar to uniform value bindings, except they specify what
    #   what attribute name binds to which attribute in the shader.
    #
    #   TODO: Actually use these bindings. However, that kind of depends on a more freeform
    #   MeshData object as freeform bindings are rather useless when we only have 5 supported
    #   attributes.
    #
    #   \param key The identifier used in the shader for the attribute.
    #   \param value The name to bind to this attribute.
    def addAttributeBinding(self, key, value):
        self._attribute_bindings[key] = value

    ##  Remove an attribute binding.
    #
    #   \param key The name of the attribute binding to remove.
    def removeAttributeBinding(self, key):
        if key not in self._attribute_bindings:
            return

        del self._attribute_bindings[key]

    def _matrixToQMatrix4x4(self, m):
        return QMatrix4x4(m.at(0, 0), m.at(0, 1), m.at(0, 2), m.at(0, 3), m.at(1, 0), m.at(1, 1), m.at(1, 2), m.at(1, 3),
            m.at(2, 0), m.at(2, 1), m.at(2, 2), m.at(2, 3), m.at(3, 0), m.at(3, 1), m.at(3, 2), m.at(3, 3))

    def _setUniformValueDirect(self, uniform, value):
        if type(value) is Vector:
            self._shader_program.setUniformValue(uniform, QVector3D(value.x, value.y, value.z))
        elif type(value) is Matrix:
            self._shader_program.setUniformValue(uniform, self._matrixToQMatrix4x4(value))
        elif type(value) is Color:
            self._shader_program.setUniformValue(uniform,
                QColor(value.r * 255, value.g * 255, value.b * 255, value.a * 255))
        elif type(value) is list and len(value) is 2:
            self._shader_program.setUniformValue(uniform, QVector2D(value[0], value[1]))
        elif type(value) is list and len(value) is 3:
            self._shader_program.setUniformValue(uniform, QVector3D(value[0], value[1], value[2]))
        elif type(value) is list and len(value) is 4:
            self._shader_program.setUniformValue(uniform, QVector4D(value[0], value[1], value[2], value[3]))
        elif type(value) is list and type(value[0]) is list and len(value[0]) is 2:
            self._shader_program.setUniformValueArray(uniform, [QVector2D(i[0], i[1]) for i in value])
        else:
            self._shader_program.setUniformValue(uniform, value)
Esempio n. 50
0
class LogoRenderer():#protected QOpenGLFunctions
    """docstring for LogoRenderer"""
    def __init__(self):
        super(LogoRenderer, self).__init__()
        self.m_fAngle = None
        self.m_fScale = None
        self.vertices = []
        self.normals = []
        self.program1 = QOpenGLShaderProgram()
        self.vertexAttr1 = 0
        self.normalAttr1 = 0
        self.matrixUniform1 = 0

        ver = QOpenGLVersionProfile()
        ver.setVersion(2, 1)
        cntx = QOpenGLContext.currentContext()
        #print("QOpenGLContext:", cntx, ver)
        fmt = cntx.format()
        fmt.setVersion(2, 1)
        cntx.setFormat(fmt)
        self.gl = cntx.versionFunctions(ver)


    def render(self):
        self.gl.glDepthMask(True)

        self.gl.glClearColor(0.5, 0.5, 0.7, 1.0)
        self.gl.glClear(self.gl.GL_COLOR_BUFFER_BIT | self.gl.GL_DEPTH_BUFFER_BIT)

        self.gl.glTexParameteri(self.gl.GL_TEXTURE_2D, self.gl.GL_TEXTURE_MIN_FILTER, self.gl.GL_LINEAR )
        self.gl.glTexParameteri(self.gl.GL_TEXTURE_2D, self.gl.GL_TEXTURE_MAG_FILTER, self.gl.GL_LINEAR )

        self.gl.glFrontFace(self.gl.GL_CW)
        self.gl.glCullFace(self.gl.GL_FRONT)
        self.gl.glEnable(self.gl.GL_CULL_FACE)
        self.gl.glEnable(self.gl.GL_DEPTH_TEST)

        modelview = QMatrix4x4()
        modelview.rotate(self.m_fAngle, 0.0, 1.0, 0.0)
        modelview.rotate(self.m_fAngle, 1.0, 0.0, 0.0)
        modelview.rotate(self.m_fAngle, 0.0, 0.0, 1.0)
        modelview.scale(self.m_fScale)
        modelview.translate(0.0, -0.2, 0.0)

        self.program1.bind()
        self.program1.setUniformValue(self.matrixUniform1, modelview)
        self.paintQtLogo()
        self.program1.release()

        self.gl.glDisable(self.gl.GL_DEPTH_TEST)
        self.gl.glDisable(self.gl.GL_CULL_FACE)

        self.m_fAngle += 1.0

    def initialize(self):
        #print("initialize.gls")
        self.gl.initializeOpenGLFunctions()

        self.gl.glClearColor(0.1, 0.1, 0.2, 1.0)

        vshader1 = QOpenGLShader(QOpenGLShader.Vertex, self.program1)
        vsrc1 = str("attribute highp vec4 vertex;\n"
                "attribute mediump vec3 normal;\n"
                "uniform mediump mat4 matrix;\n"
                "varying mediump vec4 color;\n"
                "void main(void)\n"
                "{\n"
                "    vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n"
                "    float angle = max(dot(normal, toLight), 0.0);\n"
                "    vec3 col = vec3(0.40, 1.0, 0.0);\n"
                "    color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n"
                "    color = clamp(color, 0.0, 1.0);\n"
                "    gl_Position = matrix * vertex;\n"
                "}\n")
        vshader1.compileSourceCode(vsrc1)

        fshader1 = QOpenGLShader(QOpenGLShader.Fragment, self.program1)
        fsrc1 = str("varying mediump vec4 color;\n"
                "void main(void)\n"
                "{\n"
                "    gl_FragColor = color;\n"
                "}\n")
        fshader1.compileSourceCode(fsrc1)

        self.program1.addShader(vshader1)
        self.program1.addShader(fshader1)
        self.program1.link()

        self.vertexAttr1 = self.program1.attributeLocation("vertex")
        self.normalAttr1 = self.program1.attributeLocation("normal")
        self.matrixUniform1 = self.program1.uniformLocation("matrix")

        self.gl.glTexParameteri(self.gl.GL_TEXTURE_2D, self.gl.GL_TEXTURE_MIN_FILTER, self.gl.GL_LINEAR )
        self.gl.glTexParameteri(self.gl.GL_TEXTURE_2D, self.gl.GL_TEXTURE_MAG_FILTER, self.gl.GL_LINEAR )

        self.m_fAngle = 0
        self.m_fScale = 1
        self.createGeometry()

    def paintQtLogo(self):
        self.program1.enableAttributeArray(self.normalAttr1)
        self.program1.enableAttributeArray(self.vertexAttr1)
        self.program1.setAttributeArray(self.vertexAttr1, self.vertices)
        self.program1.setAttributeArray(self.normalAttr1, self.normals)
        self.gl.glDrawArrays(self.gl.GL_TRIANGLES, 0, len(self.vertices))
        self.program1.disableAttributeArray(self.normalAttr1)
        self.program1.disableAttributeArray(self.vertexAttr1)

    def createGeometry(self):
        self.vertices.clear()
        self.normals.clear()

        x1 = +0.06
        y1 = -0.14
        x2 = +0.14
        y2 = -0.06
        x3 = +0.08
        y3 = +0.00
        x4 = +0.30
        y4 = +0.22

        self.quad(x1, y1, x2, y2, y2, x2, y1, x1)
        self.quad(x3, y3, x4, y4, y4, x4, y3, x3)

        self.extrude(x1, y1, x2, y2)
        self.extrude(x2, y2, y2, x2)
        self.extrude(y2, x2, y1, x1)
        self.extrude(y1, x1, x1, y1)
        self.extrude(x3, y3, x4, y4)
        self.extrude(x4, y4, y4, x4)
        self.extrude(y4, x4, y3, x3)

        NumSectors = 100

        for i in range(NumSectors):
            angle1 = (i * 2 * math.pi) / NumSectors
            x5 = 0.30 * math.sin(angle1)
            y5 = 0.30 * math.cos(angle1)
            x6 = 0.20 * math.sin(angle1)
            y6 = 0.20 * math.cos(angle1)

            angle2 = ((i + 1) * 2 * math.pi) / NumSectors
            x7 = 0.20 * math.sin(angle2)
            y7 = 0.20 * math.cos(angle2)
            x8 = 0.30 * math.sin(angle2)
            y8 = 0.30 * math.cos(angle2)

            self.quad(x5, y5, x6, y6, x7, y7, x8, y8)

            self.extrude(x6, y6, x7, y7)
            self.extrude(x8, y8, x5, y5)
        

        for i in range(len(self.vertices)):
            self.vertices[i] *= 2.0



    def quad(self, x1, y1, x2, y2, x3, y3, x4, y4):
        #print("quad inicio")
        self.vertices.append(QVector3D(x1, y1, -0.05))
        self.vertices.append(QVector3D(x2, y2, -0.05))
        self.vertices.append(QVector3D(x4, y4, -0.05))

        self.vertices.append(QVector3D(x3, y3, -0.05))
        self.vertices.append(QVector3D(x4, y4, -0.05))
        self.vertices.append(QVector3D(x2, y2, -0.05))

        n = QVector3D.normal(QVector3D(x2 - x1, y2 - y1, 0.0), QVector3D(x4 - x1, y4 - y1, 0.0))

        for i in range(6):
            self.normals.append(n)

        self.vertices.append(QVector3D(x4, y4, 0.05))
        self.vertices.append(QVector3D(x2, y2, 0.05))
        self.vertices.append(QVector3D(x1, y1, 0.05))

        self.vertices.append(QVector3D(x2, y2, 0.05))
        self.vertices.append(QVector3D(x4, y4, 0.05))
        self.vertices.append(QVector3D(x3, y3, 0.05))

        n = QVector3D.normal(QVector3D(x2 - x4, y2 - y4, 0.0), QVector3D(x1 - x4, y1 - y4, 0.0))

        for i in range(6):
            self.normals.append(n)
        #print("quad fin")

    def extrude(self, x1, y1, x2, y2):
        #print("extrude inicio")
        self.vertices.append(QVector3D(x1, y1, +0.05))
        self.vertices.append(QVector3D(x2, y2, +0.05))
        self.vertices.append(QVector3D(x1, y1, -0.05))

        self.vertices.append(QVector3D(x2, y2, -0.05))
        self.vertices.append(QVector3D(x1, y1, -0.05))
        self.vertices.append(QVector3D(x2, y2, +0.05))

        n = QVector3D.normal(QVector3D(x2 - x1, y2 - y1, 0.0), QVector3D(0.0, 0.0, -0.1))

        for i in range(6):
            self.normals.append(n)
Esempio n. 51
0
class QtGL2Material(Material):
    def __init__(self, renderer):
        super().__init__()

        self._gl = renderer._gl

        self._shader_program = None
        self._uniform_indices = {}
        self._attribute_indices = {}
        self._uniform_values = {}
        self._bound = False
        self._textures = {}

    def loadVertexShader(self, file):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        self._shader_program.addShaderFromSourceFile(QOpenGLShader.Vertex, file)

    def loadFragmentShader(self, file):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        self._shader_program.addShaderFromSourceFile(QOpenGLShader.Fragment, file)

    def build(self):
        if not self._shader_program:
            Logger.log("e", "No shader sources loaded")
            return

        self._shader_program.link()

    def setUniformValue(self, name, value, **kwargs):
        if not self._shader_program:
            return

        cache = True
        if "cache" in kwargs:
            cache = kwargs["cache"]

        if name not in self._uniform_indices:
            self._uniform_indices[name] = self._shader_program.uniformLocation(name)

        uniform = self._uniform_indices[name]
        if uniform == -1:
            return

        if cache:
            self._uniform_values[uniform] = value

        if self._bound:
            self._setUniformValueDirect(uniform, value)

    def setUniformTexture(self, name, file):
        if not self._shader_program:
            return

        if name not in self._uniform_indices:
            self._uniform_indices[name] = self._shader_program.uniformLocation(name)

        index = self._uniform_indices[name]

        texture = QOpenGLTexture(QImage(file).mirrored())
        texture.setMinMagFilters(QOpenGLTexture.Linear, QOpenGLTexture.Linear)
        self._textures[index] = texture

        self._uniform_values[index] = 1

        if self._bound:
            texture = self._textures[index]
            texture.bind()
            self._setUniformValueDirect(index, texture.textureId())

    def enableAttribute(self, name, type, offset, stride = 0):
        if not self._shader_program:
            return

        self.bind()

        if name not in self._attribute_indices:
            self._attribute_indices[name] = self._shader_program.attributeLocation(name)

        attribute = self._attribute_indices[name]
        if attribute == -1:
            return

        if type is "int":
            self._shader_program.setAttributeBuffer(attribute, self._gl.GL_INT, offset, 1, stride)
        elif type is "float":
            self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 1, stride)
        elif type is "vector2f":
            self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 2, stride)
        elif type is "vector3f":
            self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 3, stride)
        elif type is "vector4f":
            self._shader_program.setAttributeBuffer(attribute, self._gl.GL_FLOAT, offset, 4, stride)

        self._shader_program.enableAttributeArray(attribute)


    def disableAttribute(self, name):
        if not self._shader_program:
            return

        if name not in self._attribute_indices:
            return

        self._shader_program.disableAttributeArray(self._attribute_indices[name])

    def bind(self):
        if not self._shader_program or not self._shader_program.isLinked():
            return

        if self._bound:
            return

        self._bound = True
        self._shader_program.bind()

        for uniform in self._uniform_values:
            if uniform in self._textures:
                texture = self._textures[uniform]
                texture.bind()
                self._setUniformValueDirect(uniform, 0)
            else:
                self._setUniformValueDirect(uniform, self._uniform_values[uniform])

    def release(self):
        if not self._shader_program or not self._bound:
            return

        for texture in self._textures.values():
            texture.release()

        self._bound = False
        self._shader_program.release()

    def _matrixToQMatrix4x4(self, m):
        return QMatrix4x4(m.at(0,0), m.at(0, 1), m.at(0, 2), m.at(0, 3),
                          m.at(1,0), m.at(1, 1), m.at(1, 2), m.at(1, 3),
                          m.at(2,0), m.at(2, 1), m.at(2, 2), m.at(2, 3),
                          m.at(3,0), m.at(3, 1), m.at(3, 2), m.at(3, 3))

    def _setUniformValueDirect(self, uniform, value):
        if type(value) is Vector:
            self._shader_program.setUniformValue(uniform, QVector3D(value.x, value.y, value.z))
        elif type(value) is Matrix:
            self._shader_program.setUniformValue(uniform, self._matrixToQMatrix4x4(value))
        elif type(value) is Color:
            self._shader_program.setUniformValue(uniform, QColor(value.r * 255, value.g * 255, value.b * 255, value.a * 255))
        elif type(value) is list and len(value) is 2:
            self._shader_program.setUniformValue(uniform, QVector2D(value[0], value[1]))
        elif type(value) is list and len(value) is 3:
            self._shader_program.setUniformValue(uniform, QVector3D(value[0], value[1], value[2]))
        elif type(value) is list and len(value) is 4:
            self._shader_program.setUniformValue(uniform, QVector4D(value[0], value[1], value[2], value[3]))
        else:
            self._shader_program.setUniformValue(uniform, value)
Esempio n. 52
0
class GLSliceWidget(QtOpenGL.QGLWidget):
    _dataModelChanged = QtCore.pyqtSignal()

    def __init__(self, parent=None, interpolation="linear", **kwargs):
        logger.debug("init")

        super(GLSliceWidget, self).__init__(parent, **kwargs)

        self.renderUpdate = True
        self.parent = parent

        self.setAcceptDrops(True)

        self.texture_LUT = None
        self.setTransform(TransformModel())

        self.renderTimer = QtCore.QTimer(self)
        self.renderTimer.setInterval(50)
        self.renderTimer.timeout.connect(self.onRenderTimer)
        self.renderTimer.start()

        self.dataModel = None

        self.dataPos = 0
        self.slicePos = 0

        self.zoom_fac = 1.
        self.zoom_x = 0.5
        self.zoom_y = 0.5
        # the center in tex coords
        self.zoom_cx = 0.5
        self.zoom_cy = 0.5

        interpolation_vals = ("linear", "nearest")
        if not interpolation in interpolation_vals:
            raise KeyError("interpolation = '%s' not defined ,valid: %s" % (interpolation, str(interpolation_vals)))

        self.interp = (interpolation =="linear")
        # self.refresh()

    def setModel(self, dataModel):
        logger.debug("setModel")

        self.dataModel = dataModel

        if self.dataModel:
            self.transform.setModel(dataModel)

            self.dataModel._dataSourceChanged.connect(self.dataSourceChanged)
            self.dataModel._dataPosChanged.connect(self.dataPosChanged)
            self._dataModelChanged.connect(self.dataModelChanged)
            self._dataModelChanged.emit()

    def setTransform(self, transform):
        self.transform = transform
        self.transform._transformChanged.connect(self.refresh)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        for url in event.mimeData().urls():
            path = url.toLocalFile().toLocal8Bit().data()
            if self.dataModel:
                self.dataModel.loadFromPath(path, prefetchSize=self.N_PREFETCH)
            else:
                self.setModel(DataModel.fromPath(path, prefetchSize=self.N_PREFETCH))

    def set_colormap(self, name):
        """arr should be of shape (N,3) and gives the rgb components of the colormap"""

        try:
            arr = spimagine.config.__COLORMAPDICT__[name]
            self.makeCurrent()
            self.texture_LUT = fillTexture2d(arr.reshape((1,) + arr.shape), self.texture_LUT, self.interp)
        except:
            print("could not load colormap %s" % name)

    def set_colormap_rgb(self, color=[1., 1., 1.]):
        self._set_colormap_array(outer(linspace(0, 1., 255), np.array(color)))

    def _set_colormap_array(self, arr):
        """arr should be of shape (N,3) and gives the rgb components of the colormap"""

        self.makeCurrent()
        self.texture_LUT = fillTexture2d(arr.reshape((1,) + arr.shape), self.texture_LUT, self.interp)
        self.refresh()

    def initializeGL(self):

        self.resized = True

        self.output = zeros((100, 100))

        logger.debug("initializeGL")

        self.programTex = QOpenGLShaderProgram()
        self.programTex.addShaderFromSourceCode(QOpenGLShader.Vertex, vertShaderTex)
        self.programTex.addShaderFromSourceCode(QOpenGLShader.Fragment, fragShaderTex)
        self.programTex.link()
        self.programTex.bind()
        logger.debug("GLSL programTex log:%s", self.programTex.log())

        glClearColor(0, 0, 0, 1.)

        self.texture = None

        self.quadCoord = np.array([[-1., -1., 0.],
                                   [1., -1., 0.],
                                   [1., 1., 0.],
                                   [1., 1., 0.],
                                   [-1., 1., 0.],
                                   [-1., -1., 0.]])

        self.quadCoordTex = np.array([[0, 0],
                                      [1., 0.],
                                      [1., 1.],
                                      [1., 1.],
                                      [0, 1.],
                                      [0, 0]])

        self.set_colormap(spimagine.config.__DEFAULTCOLORMAP__)

        glDisable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    def dataModelChanged(self):
        # if self.dataModel:
        #     self.transform.reset(amin(self.dataModel[0]),
        #                          amax(self.dataModel[0]),
        #                          self.dataModel.stackUnits())
        #

        self.refresh()

    def dataSourceChanged(self):
        # self.transform.reset(amin(self.dataModel[0]),
        #                      amax(self.dataModel[0]),
        #                      self.dataModel.stackUnits())
        self.refresh()

    def dataPosChanged(self, pos):
        self.dataPos = pos
        self.refresh()

    def refresh(self):
        # if self.parentWidget() and self.dataModel:
        #     self.parentWidget().setWindowTitle("SpImagine %s"%self.dataModel.name())
        self.renderUpdate = True

    def resizeGL(self, width, height):
        # height = max(10,height)

        self._viewport_width, self._viewport_height = width, height

        self.resized = True
        self.resetViewPort()

    def getDataWidthHeight(self):
        if not self.dataModel:
            return 1, 1

        dim = array(self.dataModel.size()[1:])[::-1].astype(np.float32)

        dim *= array(self.transform.stackUnits)

        if self.transform.sliceDim == 0:
            dim = dim[[2, 1]]
        elif self.transform.sliceDim == 1:
            dim = dim[[0, 2]]
        elif self.transform.sliceDim == 2:
            dim = dim[[0, 1]]

        w, h = dim[0], dim[1]

        fac = min(1. * self._viewport_width / w, 1. * self._viewport_height / h)

        return int(fac * w), int(fac * h)

    def resetViewPort(self):
        w, h = self.getDataWidthHeight()
        glViewport((self._viewport_width - w) // 2, (self._viewport_height - h) // 2, w, h)

    def paintGL(self):

        self.makeCurrent()

        if not glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE:
            return

        # hack
        if self.resized:
            self.resetViewPort()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        if self.dataModel:
            # Draw the render texture
            self.programTex.bind()

            self.texture = fillTexture2d(self.output, self.texture, self.interp)

            glEnable(GL_TEXTURE_2D)
            glDisable(GL_DEPTH_TEST)

            self.programTex.enableAttributeArray("position")
            self.programTex.enableAttributeArray("texcoord")
            self.programTex.setAttributeArray("position", self.quadCoord)
            self.programTex.setAttributeArray("texcoord",
                                              self.tex_coords_from_xyzoom(self.zoom_x, self.zoom_y, self.zoom_fac))

            glActiveTexture(GL_TEXTURE0)
            glBindTexture(GL_TEXTURE_2D, self.texture)
            self.programTex.setUniformValue("texture", 0)

            glActiveTexture(GL_TEXTURE1)
            glBindTexture(GL_TEXTURE_2D, self.texture_LUT)
            self.programTex.setUniformValue("texture_LUT", 1)

            glDrawArrays(GL_TRIANGLES, 0, len(self.quadCoord))

    def render(self):
        logger.debug("render")
        if self.dataModel:
            if self.transform.sliceDim == 0:
                out = fliplr(self.dataModel[self.transform.dataPos][:, :, self.transform.slicePos].T)
            elif self.transform.sliceDim == 1:
                out = self.dataModel[self.transform.dataPos][:, self.transform.slicePos, :]
            elif self.transform.sliceDim == 2:
                out = self.dataModel[self.transform.dataPos][self.transform.slicePos, :, :]

            min_out, max_out = self.transform.minVal, self.transform.maxVal

            if max_out > min_out:
                self.output = np.maximum(0,(1. * (out - min_out) / (max_out - min_out))) ** self.transform.gamma
            else:
                self.output = np.zeros_like(out)

            logger.debug("render: output range = %s" % ([amin(self.output), amax(self.output)]))

    def saveFrame(self, fName):
        """FIXME: scaling behaviour still hast to be implemented (e.g. after setGamma)"""
        logger.info("saving frame as %s", fName)

        self.render()
        self.paintGL()
        glFlush()
        self.grabFrameBuffer().save(fName)

    def onRenderTimer(self):
        if self.renderUpdate:
            self.render()
            self.renderUpdate = False
            self.updateGL()

    def tex_coords_from_xyzoom(self, x0, y0, zoom):
        """returns array of texccords corners when zoomed
        in onto x0,y0 \in [0,1]
        
        zoom == 1   --> fully zoomed out
        zoom == 0   --> fully zoomed in (to x0,y0)
        """

        q0 = create_quad_coords([0, 1, 0, 1])
        q1 = create_quad_coords([x0, x0, y0, y0])

        return zoom * q0 + (1. - zoom) * q1

    def getRelativeCoords(self, x0, y0):
        w, h = self.getDataWidthHeight()

        w = w * self.width() / self._viewport_width
        h = w * self.height() / self._viewport_height

        x = 2. * (x0 - .5 * (self.width() - w)) / w - 1
        y = 2. * (y0 - .5 * (self.height() - h)) / h - 1

        x = (x0 - .5 * (self.width() - w)) / w
        y = 1 - (y0 - .5 * (self.height() - h)) / h

        return x, y

    def mousePressEvent(self, event):
        super(GLSliceWidget, self).mousePressEvent(event)

        if event.buttons() == QtCore.Qt.LeftButton:
            self._x0, self._y0 = self.getRelativeCoords(event.x(), event.y())

    def mouseMoveEvent(self, event):

        if event.buttons() == QtCore.Qt.LeftButton:
            x, y = self.getRelativeCoords(event.x(), event.y())
            self.zoom_x += self.zoom_fac * (self._x0 - x)
            self.zoom_y += self.zoom_fac * (self._y0 - y)
            self._x0, self._y0 = x, y
            self.zoom_x, self.zoom_y = clip(self.zoom_x, 0, 1), clip(self.zoom_y, 0, 1)

        self.refresh()

    def wheelEvent(self, event):
        # get the zoom factor

        # print self.zoom_x,self.zoom_y
        # x, y = self.getRelativeCoords(event.x(),event.y())
        # self.zoom_x , self.zoom_y = clip(x ,0,1), clip(y,0,1)



        self.zoom_fac *= 1.4 ** (-event.angleDelta().y() / 1000.)
        self.zoom_fac = clip(self.zoom_fac, 0, 1.)

        self.refresh()
Esempio n. 53
0
    def loadVertexShader(self, file):
        if not self._shader_program:
            self._shader_program = QOpenGLShaderProgram()

        self._shader_program.addShaderFromSourceFile(QOpenGLShader.Vertex, file)