def draw_callback_px(self, context):
    kha_SystemImpl.frame()
    bgl.glUseProgram(0)
    bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, 0)
    bgl.glBindBuffer(bgl.GL_ELEMENT_ARRAY_BUFFER, 0)
    bgl.glDisable(bgl.GL_DEPTH_TEST)
    bgl.glDepthFunc(bgl.GL_ALWAYS)
Example #2
0
    def enable(self):
        try:
            if DEBUG_PRINT:
                print('enabling shader <==================')
                if self.checkErrors:
                    self.drawing.glCheckError(
                        'something broke before enabling shader program (%s, %d)'
                        % (self.name, self.shaderProg))
            bgl.glUseProgram(self.shaderProg)
            if self.checkErrors:
                self.drawing.glCheckError(
                    'something broke after enabling shader program (%s,%d)' %
                    (self.name, self.shaderProg))

            # special uniforms
            # - uMVPMatrix works around deprecated gl_ModelViewProjectionMatrix
            if 'uMVPMatrix' in self.shaderVars:
                mvpmatrix = bpy.context.region_data.perspective_matrix
                mvpmatrix_buffer = bgl.Buffer(bgl.GL_FLOAT, [4, 4], mvpmatrix)
                self.assign('uMVPMatrix', mvpmatrix_buffer)

            if self.funcStart: self.funcStart(self)
        except Exception as e:
            print('Error with using shader: ' + str(e))
            bgl.glUseProgram(0)
 def enable(self):
     try:
         bgl.glUseProgram(self.shaderProg)
         if self.funcStart: self.funcStart(self)
     except Exception as e:
         print('Error with using shader: ' + str(e))
         bgl.glUseProgram(0)
Example #4
0
 def draw(self):
     bgl.glUseProgram(self.program)
     bgl.glActiveTexture(bgl.GL_TEXTURE0)
     bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.texture[0])
     bgl.glBindVertexArray(self.vertex_array[0])
     bgl.glDrawArrays(bgl.GL_TRIANGLE_FAN, 0, 4)
     bgl.glBindVertexArray(0)
     bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
Example #5
0
 def useFor(self, funcCallback):
     try:
         bgl.glUseProgram(self.shaderProg)
         if self.funcStart: self.funcStart(self)
         funcCallback(self)
     except Exception as e:
         print('ERROR WITH USING SHADER: ' + str(e))
     finally:
         bgl.glUseProgram(0)
Example #6
0
 def useFor(self,funcCallback):
     try:
         bgl.glUseProgram(self.shaderProg)
         if self.funcStart: self.funcStart(self)
         funcCallback(self)
     except Exception as e:
         print('ERROR WITH USING SHADER: ' + str(e))
     finally:
         bgl.glUseProgram(0)
Example #7
0
 def disable(self):
     if DEBUG_PRINT:
         print('disabling shader <=================')
     self.checkErrors(f'disable program ({self.name}, {self.shaderProg}) pre')
     try:
         if self.funcEnd: self.funcEnd(self)
     except Exception as e:
         print('Error with shader: ' + str(e))
     bgl.glUseProgram(0)
     self.checkErrors(f'disable program ({self.name}, {self.shaderProg}) post')
Example #8
0
def gpu_Indices_use_clip_planes(rv3d, value):
    if rv3d.use_clip_planes:
        planes = bgl.Buffer(bgl.GL_FLOAT, (6, 4), rv3d.clip_planes)

        _store_current_shader_state(PreviousGLState)
        bgl.glUseProgram(GPU_Indices_Mesh.shader.program)
        bgl.glUniform1i(GPU_Indices_Mesh.unif_use_clip_planes, value)

        bgl.glUniform4fv(GPU_Indices_Mesh.unif_clip_plane, 4, planes)

        _restore_shader_state(PreviousGLState)
Example #9
0
 def disable(self):
     if DEBUG_PRINT:
         print('disabling shader <=================')
     if self.checkErrors:
         self.drawing.glCheckError('disable program (%d) pre' % self.shaderProg)
     try:
         if self.funcEnd: self.funcEnd(self)
     except Exception as e:
         print('Error with shader: ' + str(e))
     bgl.glUseProgram(0)
     if self.checkErrors:
         self.drawing.glCheckError('disable program (%d) post' % self.shaderProg)
Example #10
0
def gpu_Indices_use_clip_planes(rv3d, value):
    if rv3d.use_clip_planes:
        planes = bgl.Buffer(bgl.GL_FLOAT, (6, 4), rv3d.clip_planes)

        _store_current_shader_state(PreviousGLState)
        GPU_Indices_Mesh.init_opengl()
        bgl.glUseProgram(GPU_Indices_Mesh.shader.program)
        bgl.glUniform1i(GPU_Indices_Mesh.unif_use_clip_planes, value)

        bgl.glUniform4fv(GPU_Indices_Mesh.unif_clip_plane, 4, planes)

        _restore_shader_state(PreviousGLState)
Example #11
0
    def Draw(self, index_offset):
        self.first_index = index_offset
        bgl.glUseProgram(self.shader.program)
        bgl.glBindVertexArray(self.vao[0])

        bgl.glUniformMatrix4fv(self.unif_MV, 1, bgl.GL_TRUE, self.MV)
        bgl.glUniformMatrix4fv(self.unif_MVP, 1, bgl.GL_TRUE, self.MVP)

        if self.draw_tris:
            bgl.glUniform1f(self.unif_offset, float(index_offset)) # bgl has no glUniform1ui :\

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_tris[0])
            bgl.glEnableVertexAttribArray(self.attr_pos)
            bgl.glVertexAttribPointer(self.attr_pos, 3, bgl.GL_FLOAT, bgl.GL_FALSE, 0, self._NULL)

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_tri_indices[0])
            bgl.glEnableVertexAttribArray(self.attr_primitive_id)
            bgl.glVertexAttribPointer(self.attr_primitive_id, 1, bgl.GL_FLOAT, bgl.GL_FALSE, 0, self._NULL)

            bgl.glDrawArrays(bgl.GL_TRIANGLES, 0, self.num_tris * 3)

            index_offset += self.num_tris
            bgl.glDepthRange(-0.00005, 0.99995)

        if self.draw_edges:
            bgl.glUniform1f(self.unif_offset, float(index_offset)) #TODO: use glUniform1ui

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_edges[0])
            bgl.glVertexAttribPointer(self.attr_pos, 3, bgl.GL_FLOAT, bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_pos)

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_edge_indices[0])
            bgl.glVertexAttribPointer(self.attr_primitive_id, 1, bgl.GL_FLOAT, bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_primitive_id)

            bgl.glDrawArrays(bgl.GL_LINES, 0, self.num_edges * 2)

            index_offset += self.num_edges

        if self.draw_verts:
            bgl.glUniform1f(self.unif_offset, float(index_offset)) #TODO: use glUniform1ui

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_verts[0])
            bgl.glVertexAttribPointer(self.attr_pos, 3, bgl.GL_FLOAT, bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_pos)

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_looseverts_indices[0])
            bgl.glVertexAttribPointer(self.attr_primitive_id, 1, bgl.GL_FLOAT, bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_primitive_id)

            bgl.glDrawArrays(bgl.GL_POINTS, 0, self.num_verts)

        bgl.glDepthRange(0.0, 1.0)
Example #12
0
def draw_vertex_array(key, mode, dimensions, color):
    if key in VAO and VAO[key] and program:
        vao = VAO[key]

        bgl.glUseProgram(program)
        bgl.glUniform4f(bgl.glGetUniformLocation(program, "color"), *color)

        bgl.glEnableClientState(bgl.GL_VERTEX_ARRAY)
        bgl.glVertexPointer(dimensions, bgl.GL_FLOAT, 0, vao)
        bgl.glDrawArrays(mode, 0, int(len(vao) / dimensions))

        bgl.glDisableClientState(bgl.GL_VERTEX_ARRAY)
        bgl.glUseProgram(0)
Example #13
0
 def disable(self):
     if DEBUG_PRINT:
         print('disabling shader <=================')
     if self.checkErrors:
         self.drawing.glCheckError(
             'something broke before disabling shader program (%s,%d)' %
             (self.name, self.shaderProg))
     try:
         if self.funcEnd: self.funcEnd(self)
     except Exception as e:
         print('Error with shader: ' + str(e))
     bgl.glUseProgram(0)
     if self.checkErrors:
         self.drawing.glCheckError(
             'something broke after disabling shader program (%s,%d)' %
             (self.name, self.shaderProg))
Example #14
0
    def draw(self, index_offset):
        self.first_index = index_offset
        bgl.glUseProgram(self.shader.program)
        bgl.glBindVertexArray(self.vao[0])
        bgl.glUniformMatrix4fv(self.unif_MVP, 1, bgl.GL_TRUE, self.MVP)
        # bgl.glUniform1f(self.unif_size, float(2.0))

        if self.draw_segs:
            self.bind(self.vbo_segs_co, self.vbo_segs, index_offset)
            bgl.glDrawArrays(bgl.GL_LINES, 0, self.num_segs * 2)
            index_offset += self.num_segs

        if self.draw_origin:
            self.bind(self.vbo_origin_co, self.vbo_origin, index_offset)
            bgl.glDrawArrays(bgl.GL_POINTS, 0, self.num_origins)
            index_offset += self.num_origins

        bgl.glBindVertexArray(0)
Example #15
0
    def enable(self):
        try:
            if DEBUG_PRINT:
                print('enabling shader <==================')
            self.checkErrors(f'using program ({self.name}, {self.shaderProg}) pre')
            bgl.glUseProgram(self.shaderProg)
            self.checkErrors(f'using program ({self.name}, {self.shaderProg}) post')

            # # special uniforms
            # # - uMVPMatrix works around deprecated gl_ModelViewProjectionMatrix
            # if 'uMVPMatrix' in self.shaderVars:
            #     mvpmatrix = bpy.context.region_data.perspective_matrix
            #     mvpmatrix_buffer = bgl.Buffer(bgl.GL_FLOAT, [4,4], mvpmatrix)
            #     self.assign('uMVPMatrix', mvpmatrix_buffer)

            if self.funcStart: self.funcStart(self)
        except Exception as e:
            print(f'Addon Common: Error with using shader: {e}')
            bgl.glUseProgram(0)
    def draw(self, index_offset):

        self.first_index = index_offset

        bgl.glUseProgram(self.shader.program)
        check_error("glUseProgram")

        bgl.glBindVertexArray(self.vao[0])
        check_error("glBindVertexArray(self.vao[0])")
        bgl.glUniformMatrix4fv(self.unif_MVP, 1, bgl.GL_TRUE, self.MVP)
        check_error("glUniformMatrix4fv")
        # 2.91 - require sequence of floats
        # self.shader.uniform_float("MVP", np.reshape(self.MVP, 16))

        if self.draw_segs:
            self.bind(self.vbo_segs_co, self.vbo_segs, index_offset)
            check_error("draw_segs bind")
            # 2.91
            # self.shader.uniform_float("offset", float(index_offset))
            bgl.glDrawArrays(bgl.GL_LINES, 0, self.num_segs * 2)
            check_error("draw_segs glDrawArrays")
            index_offset += self.num_segs

        if self.draw_origin:
            self.bind(self.vbo_origin_co, self.vbo_origin, index_offset)
            check_error("draw_origin bind")
            # 2.91
            # self.shader.uniform_float("offset", float(index_offset))
            bgl.glDrawArrays(bgl.GL_POINTS, 0, self.num_origins)
            check_error("draw_origin glDrawArrays")
            index_offset += self.num_origins

        if self.draw_bounds:
            self.bind(self.vbo_bounds_co, self.vbo_bounds, index_offset)
            check_error("draw_bounds bind")
            # 2.91
            # self.shader.uniform_float("offset", float(index_offset))
            bgl.glDrawArrays(bgl.GL_POINTS, 0, self.num_bounds)
            check_error("draw_bounds glDrawArrays")
            index_offset += self.num_bounds

        bgl.glBindVertexArray(0)
        check_error("glBindVertexArray(0)")
Example #17
0
    def view_draw(self, context):

        verco = [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)]
        texco = [(1.0, 1.0), (0.0, 1.0), (0.0, 0.0), (1.0, 0.0)]

        viewport = bgl.Buffer(bgl.GL_INT, [4])

        bgl.glDisable(bgl.GL_DEPTH_TEST)

        bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport)

        bgl.glViewport(viewport[0], viewport[1], viewport[2], viewport[3])

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()

        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()

        bgl.glUseProgram(self.program)
        wind = glGetUniformLocation(self.program, "u_wind")
        res = glGetUniformLocation(self.program, "u_resolution")
        size = glGetUniformLocation(self.program, "u_size")

        glUniform2fv(wind, 1, [150.0, 150.0])
        glUniform1f(size, 250.0)
        glUniform1f(res, 512.0)

        bgl.glBegin(bgl.GL_QUADS)
        for i in range(4):
            bgl.glTexCoord3f(texco[i][0], texco[i][1], 1.0)
            bgl.glVertex2f(verco[i][0], verco[i][1])
        bgl.glEnd()

        bgl.glUseProgram(0)

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPopMatrix()

        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPopMatrix()
Example #18
0
    def enable(self):
        try:
            if DEBUG_PRINT:
                print('enabling shader <==================')
                if self.checkErrors:
                    self.drawing.glCheckError('using program (%d) pre' % self.shaderProg)
            bgl.glUseProgram(self.shaderProg)
            if self.checkErrors:
                self.drawing.glCheckError('using program (%d) post' % self.shaderProg)

            # special uniforms
            # - uMVPMatrix works around deprecated gl_ModelViewProjectionMatrix
            if 'uMVPMatrix' in self.shaderVars:
                mvpmatrix = bpy.context.region_data.perspective_matrix
                mvpmatrix_buffer = bgl.Buffer(bgl.GL_FLOAT, [4,4], mvpmatrix)
                self.assign('uMVPMatrix', mvpmatrix_buffer)

            if self.funcStart: self.funcStart(self)
        except Exception as e:
            print('Error with using shader: ' + str(e))
            bgl.glUseProgram(0)
Example #19
0
	def bindUniformf(self, name):
		self.findProgram()
		bgl.glUseProgram(self.program)
		pname = self.__class__.__name__ + '_' + name
		bgl.glUniform1f(bgl.glGetUniformLocation(self.program, pname), getattr(self, name))
		
Example #20
0
def gpu_Indices_enable_state():
    _store_current_shader_state(PreviousGLState)

    GPU_Indices_Mesh.init_opengl()
    bgl.glUseProgram(GPU_Indices_Mesh.shader.program)
Example #21
0
def _restore_shader_state(cls):
    bgl.glUseProgram(cls.cur_program[0])
    bgl.glBindVertexArray(cls.cur_vao[0])
    bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, cls.cur_vbo[0])
    bgl.glBindBuffer(bgl.GL_ELEMENT_ARRAY_BUFFER, cls.cur_ebo[0])
Example #22
0
def gpu_Indices_enable_state():
    _store_current_shader_state(PreviousGLState)
    bgl.glUseProgram(GPU_Indices.shader.program)
    bgl.glEnableVertexAttribArray(GPU_Indices.attr_pos)
    bgl.glEnableVertexAttribArray(GPU_Indices.attr_primitive_id)
Example #23
0
    def execute(self, refholder):
        # pass
        tr = self.nodeTree.properties.TextureResolution
        print("begining execution " + str(tr))
        # compute A'
        mask = np.array([[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]])
        # Input data pixels
        A = self.inputs[0].getPixels()
        B = self.inputs[1].getPixels()

        # print(A)

        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM,
                          self.rdData[self.name]["prev_program"])
        bgl.glUseProgram(self.rdData[self.name]["program"])

        #set any uniforms needed
        bgl.glUniform1f(self.rdData[self.name]["feed_loc"],
                        self.inputs[2].value)
        bgl.glUniform1f(self.rdData[self.name]["kill_loc"],
                        self.inputs[3].value)
        bgl.glUniform1f(self.rdData[self.name]["da_loc"], self.inputs[4].value)
        bgl.glUniform1f(self.rdData[self.name]["db_loc"], self.inputs[5].value)
        bgl.glUniform1f(self.rdData[self.name]["dt_loc"], self.inputs[6].value)
        bgl.glUniform1f(self.rdData[self.name]["step_loc"], 1 / tr)

        bgl.glDisable(bgl.GL_SCISSOR_TEST)
        bgl.glViewport(0, 0, tr, tr)

        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, 1, 0, 1)

        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glActiveTexture(bgl.GL_TEXTURE0)

        channels = []
        if self.channels == '0':
            channels = [0]
        elif self.channels == '1':
            channels = [0, 1, 2]

        for j in channels:
            self.rdData[self.name]["npArray"][:, :, 0] = A[:, :, j]
            self.rdData[self.name]["npArray"][:, :, 1] = B[:, :, j]

            # Caution: Interfacing with Cython requires toList()
            self.rdData[self.name]["image"].pixels = self.rdData[
                self.name]["npArray"].flatten()

            self.rdData[self.name]["image"].gl_load(0, bgl.GL_LINEAR,
                                                    bgl.GL_LINEAR)

            bgl.glBindTexture(bgl.GL_TEXTURE_2D,
                              self.rdData[self.name]["image"].bindcode[0])
            bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_S,
                                bgl.GL_REPEAT)
            bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_T,
                                bgl.GL_REPEAT)

            for i in range(self.inputs[7].value):
                bgl.glClearDepth(1.0)
                bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
                bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

                bgl.glBegin(bgl.GL_TRIANGLES)

                bgl.glColor3f(1.0, 1.0, 1.0)
                bgl.glTexCoord2f(0.0, 0.0)
                bgl.glVertex2f(-1.0, -1.0)
                bgl.glTexCoord2f(1.0, 0.0)
                bgl.glVertex2f(1.0, -1.0)
                bgl.glTexCoord2f(1.0, 1.0)
                bgl.glVertex2f(1.0, 1.0)

                bgl.glColor3f(1.0, 1.0, 1.0)
                bgl.glTexCoord2f(0.0, 0.0)
                bgl.glVertex2f(-1.0, -1.0)
                bgl.glTexCoord2f(1.0, 1.0)
                bgl.glVertex2f(1.0, 1.0)
                bgl.glTexCoord2f(0.0, 1.0)
                bgl.glVertex2f(-1.0, 1.0)
                bgl.glEnd()

                bgl.glCopyTexImage2D(
                    bgl.GL_TEXTURE_2D,  #target
                    0,  #level
                    bgl.GL_RGBA,  #internalformat
                    0,  #x
                    0,  #y
                    tr,
                    tr,
                    0  #border
                )

                #glFlush glFinish or none here?
                bgl.glFinish()

            bgl.glReadPixels(0, 0, tr, tr, bgl.GL_RGBA, bgl.GL_FLOAT,
                             self.rdData[self.name]["buffer"])
            self.rdData[self.name]["image"].pixels = self.rdData[
                self.name]["buffer"][:]
            #write the image channel
            npImage = np.asarray(self.rdData[self.name]["image"].pixels,
                                 dtype="float")
            self.rdData[self.name]["npArray"] = npImage.reshape(
                tr, tr, self.rdData[self.name]["image"].channels)

            self.outputs[0].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 0], j, flatten=True)
            self.outputs[1].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 1], j, flatten=True)
            self.outputs[2].setPackedImageFromPixels(
                self.rdData[self.name]["npArray"])

            self.inputs[0].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 0], j, flatten=True)
            self.inputs[1].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 1], j, flatten=True)

            # ================================= Test bed
            # self.outputs[0].getTexture().image.copy()
            # self.outputs[1].getTexture().image.copy()
            # self.outputs[2].getTexture().image.copy()

            # nparr = np.asarray(self.outputs[0].getTexture().image.pixels, dtype="float")
            # nparr = nparr.reshape(tr, tr, 4)
            # print(nparr)

            self.rdData[self.name]["image"].gl_free()

        #restore the state so blender wont break
        bgl.glEnable(bgl.GL_SCISSOR_TEST)
        bgl.glUseProgram(self.rdData[self.name]["prev_program"][0])
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
def _restore_shader_state(cls):
    bgl.glUseProgram(cls.cur_program[0])
    bgl.glBindVertexArray(cls.cur_vao[0])
    bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, cls.cur_vbo[0])
    bgl.glBindBuffer(bgl.GL_ELEMENT_ARRAY_BUFFER, cls.cur_ebo[0])
def gpu_Indices_enable_state():
    _store_current_shader_state(PreviousGLState)

    GPU_Indices_Mesh.init_opengl()
    bgl.glUseProgram(GPU_Indices_Mesh.shader.program)
    def Draw(self, index_offset):
        self.first_index = index_offset
        bgl.glUseProgram(self.shader.program)
        bgl.glBindVertexArray(self.vao[0])

        bgl.glUniformMatrix4fv(self.unif_MV, 1, bgl.GL_TRUE, self.MV)
        bgl.glUniformMatrix4fv(self.unif_MVP, 1, bgl.GL_TRUE, self.MVP)

        if self.draw_tris:
            bgl.glUniform1f(self.unif_offset,
                            float(index_offset))  # bgl has no glUniform1ui :\

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_tris[0])
            bgl.glEnableVertexAttribArray(self.attr_pos)
            bgl.glVertexAttribPointer(self.attr_pos, 3, bgl.GL_FLOAT,
                                      bgl.GL_FALSE, 0, self._NULL)

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_tri_indices[0])
            bgl.glEnableVertexAttribArray(self.attr_primitive_id)
            bgl.glVertexAttribPointer(self.attr_primitive_id, 1, bgl.GL_FLOAT,
                                      bgl.GL_FALSE, 0, self._NULL)

            bgl.glDrawArrays(bgl.GL_TRIANGLES, 0, self.num_tris * 3)

            index_offset += self.num_tris
            bgl.glDepthRange(-0.00005, 0.99995)

        if self.draw_edges:
            bgl.glUniform1f(self.unif_offset,
                            float(index_offset))  #TODO: use glUniform1ui

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_edges[0])
            bgl.glVertexAttribPointer(self.attr_pos, 3, bgl.GL_FLOAT,
                                      bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_pos)

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_edge_indices[0])
            bgl.glVertexAttribPointer(self.attr_primitive_id, 1, bgl.GL_FLOAT,
                                      bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_primitive_id)

            bgl.glDrawArrays(bgl.GL_LINES, 0, self.num_edges * 2)

            index_offset += self.num_edges

        if self.draw_verts:
            bgl.glUniform1f(self.unif_offset,
                            float(index_offset))  #TODO: use glUniform1ui

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vbo_verts[0])
            bgl.glVertexAttribPointer(self.attr_pos, 3, bgl.GL_FLOAT,
                                      bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_pos)

            bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER,
                             self.vbo_looseverts_indices[0])
            bgl.glVertexAttribPointer(self.attr_primitive_id, 1, bgl.GL_FLOAT,
                                      bgl.GL_FALSE, 0, self._NULL)
            bgl.glEnableVertexAttribArray(self.attr_primitive_id)

            bgl.glDrawArrays(bgl.GL_POINTS, 0, self.num_verts)

        bgl.glDepthRange(0.0, 1.0)
Example #27
0
def draw_view():

    ######################
    ######## BIND ########
    ######################

    first_time = not bgl.glIsVertexArray(namespace['vao'][0])

    if first_time:
        namespace['uniform_set'] = False

        # Unlike VBOs, a VAO has to be generated and deleted from within the draw callback in which it will be bound.
        bgl.glGenVertexArrays(1, namespace['vao'])
        bgl.glBindVertexArray(namespace['vao'][0])

        float_byte_count = 4

        # Attribute: "point", 3D float vector
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, namespace['vbo_point'][0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER,
                         len(namespace['data_point']) * float_byte_count,
                         namespace['data_point'], bgl.GL_DYNAMIC_DRAW)

        bgl.glVertexAttribPointer(0, 3, bgl.GL_FLOAT, bgl.GL_FALSE, 0, None)
        bgl.glEnableVertexAttribArray(0)

        # Attribute: "color", 4D float vector
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, namespace['vbo_color'][0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER,
                         len(namespace['data_color']) * float_byte_count,
                         namespace['data_color'], bgl.GL_DYNAMIC_DRAW)

        bgl.glVertexAttribPointer(1, 4, bgl.GL_FLOAT, bgl.GL_FALSE, 0, None)
        bgl.glEnableVertexAttribArray(1)

        bgl.glBindVertexArray(0)

    ######################
    ######## DRAW ########
    ######################

    bgl.glEnable(bgl.GL_BLEND)

    bgl.glUseProgram(namespace['shader_program'])

    if not namespace['uniform_set']:
        bgl.glUniformMatrix4fv(
            namespace['perspective_uniform_location'],
            1,
            bgl.
            GL_TRUE,  # Matrices in Blender are row-major while matrices in OpenGL are column-major, so Blender's perspective matrix has to be transposed for OpenGL.
            namespace['projection_matrix'])

        # In this case I only want to update the uniform once, even though namespace['projection_matrix'] is being updated constantly.
        namespace['uniform_set'] = True

    bgl.glBindVertexArray(namespace['vao'][0])
    bgl.glDrawArrays(bgl.GL_TRIANGLES, 0, 3)

    bgl.glUseProgram(0)
    bgl.glBindVertexArray(0)

    bgl.glDisable(bgl.GL_BLEND)
Example #28
0
    def render(self, draw_data):
        io = self.io
        shader = self._bl_shader

        display_width, display_height = io.display_size
        fb_width = int(display_width * io.display_fb_scale[0])
        fb_height = int(display_height * io.display_fb_scale[1])

        if fb_width == 0 or fb_height == 0:
            return

        draw_data.scale_clip_rects(*io.display_fb_scale)

        # backup GL state
        (
            last_program,
            last_texture,
            last_active_texture,
            last_array_buffer,
            last_element_array_buffer,
            last_vertex_array,
            last_blend_src,
            last_blend_dst,
            last_blend_equation_rgb,
            last_blend_equation_alpha,
            last_viewport,
            last_scissor_box,
        ) = self._backup_integers(
            gl.GL_CURRENT_PROGRAM,
            1,
            gl.GL_TEXTURE_BINDING_2D,
            1,
            gl.GL_ACTIVE_TEXTURE,
            1,
            gl.GL_ARRAY_BUFFER_BINDING,
            1,
            gl.GL_ELEMENT_ARRAY_BUFFER_BINDING,
            1,
            gl.GL_VERTEX_ARRAY_BINDING,
            1,
            gl.GL_BLEND_SRC,
            1,
            gl.GL_BLEND_DST,
            1,
            gl.GL_BLEND_EQUATION_RGB,
            1,
            gl.GL_BLEND_EQUATION_ALPHA,
            1,
            gl.GL_VIEWPORT,
            4,
            gl.GL_SCISSOR_BOX,
            4,
        )

        last_enable_blend = gl.glIsEnabled(gl.GL_BLEND)
        last_enable_cull_face = gl.glIsEnabled(gl.GL_CULL_FACE)
        last_enable_depth_test = gl.glIsEnabled(gl.GL_DEPTH_TEST)
        last_enable_scissor_test = gl.glIsEnabled(gl.GL_SCISSOR_TEST)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendEquation(gl.GL_FUNC_ADD)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glDisable(gl.GL_CULL_FACE)
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_SCISSOR_TEST)
        gl.glActiveTexture(gl.GL_TEXTURE0)

        gl.glViewport(0, 0, int(fb_width), int(fb_height))

        ortho_projection = (2.0 / display_width, 0.0, 0.0, 0.0, 0.0,
                            2.0 / -display_height, 0.0, 0.0, 0.0, 0.0, -1.0,
                            0.0, -1.0, 1.0, 0.0, 1.0)
        shader.bind()
        shader.uniform_float("ProjMtx", ortho_projection)
        shader.uniform_int("Texture", 0)

        for commands in draw_data.commands_lists:
            size = commands.idx_buffer_size * imgui.INDEX_SIZE // 4
            address = commands.idx_buffer_data
            ptr = C.cast(address, C.POINTER(C.c_int))
            idx_buffer_np = np.ctypeslib.as_array(ptr, shape=(size, ))

            size = commands.vtx_buffer_size * imgui.VERTEX_SIZE // 4
            address = commands.vtx_buffer_data
            ptr = C.cast(address, C.POINTER(C.c_float))
            vtx_buffer_np = np.ctypeslib.as_array(ptr, shape=(size, ))
            vtx_buffer_shaped = vtx_buffer_np.reshape(-1,
                                                      imgui.VERTEX_SIZE // 4)

            idx_buffer_offset = 0
            for command in commands.commands:
                x, y, z, w = command.clip_rect
                gl.glScissor(int(x), int(fb_height - w), int(z - x),
                             int(w - y))

                vertices = vtx_buffer_shaped[:, :2]
                uvs = vtx_buffer_shaped[:, 2:4]
                colors = vtx_buffer_shaped.view(np.uint8)[:, 4 * 4:]
                colors = colors.astype('f') / 255.0

                indices = idx_buffer_np[idx_buffer_offset:idx_buffer_offset +
                                        command.elem_count]

                gl.glBindTexture(gl.GL_TEXTURE_2D, command.texture_id)

                batch = batch_for_shader(shader,
                                         'TRIS', {
                                             "Position": vertices,
                                             "UV": uvs,
                                             "Color": colors,
                                         },
                                         indices=indices)
                batch.draw(shader)

                idx_buffer_offset += command.elem_count

        # restore modified GL state
        gl.glUseProgram(last_program)
        gl.glActiveTexture(last_active_texture)
        gl.glBindTexture(gl.GL_TEXTURE_2D, last_texture)
        gl.glBindVertexArray(last_vertex_array)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, last_array_buffer)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer)
        gl.glBlendEquationSeparate(last_blend_equation_rgb,
                                   last_blend_equation_alpha)
        gl.glBlendFunc(last_blend_src, last_blend_dst)

        if last_enable_blend:
            gl.glEnable(gl.GL_BLEND)
        else:
            gl.glDisable(gl.GL_BLEND)

        if last_enable_cull_face:
            gl.glEnable(gl.GL_CULL_FACE)
        else:
            gl.glDisable(gl.GL_CULL_FACE)

        if last_enable_depth_test:
            gl.glEnable(gl.GL_DEPTH_TEST)
        else:
            gl.glDisable(gl.GL_DEPTH_TEST)

        if last_enable_scissor_test:
            gl.glEnable(gl.GL_SCISSOR_TEST)
        else:
            gl.glDisable(gl.GL_SCISSOR_TEST)

        gl.glViewport(last_viewport[0], last_viewport[1], last_viewport[2],
                      last_viewport[3])
        gl.glScissor(last_scissor_box[0], last_scissor_box[1],
                     last_scissor_box[2], last_scissor_box[3])
 def disable(self):
     bgl.glUseProgram(0)
Example #30
0
    def __init__(self, dimensions, perspective, region3d):
        self.dimensions = dimensions
        self.perspective = perspective

        width = bpy.context.scene.tina_resolution_x
        height = bpy.context.scene.tina_resolution_y
        pixels = worker.render_main(width, height, region3d)

        # Generate dummy image buffer
        pixels = bgl.Buffer(bgl.GL_INT, width * height, pixels)

        # Generate texture
        self.texture = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGenTextures(1, self.texture)
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.texture[0])
        bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA16F, width, height,
                         0, bgl.GL_RGBA, bgl.GL_UNSIGNED_INT_8_8_8_8_REV,
                         pixels)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER,
                            bgl.GL_LINEAR)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            bgl.GL_LINEAR)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

        bgl.glUseProgram(self.program)

        # Generate vertex array
        self.vertex_array = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGenVertexArrays(1, self.vertex_array)
        bgl.glBindVertexArray(self.vertex_array[0])

        texturecoord_location = bgl.glGetAttribLocation(
            self.program, "texCoord")
        position_location = bgl.glGetAttribLocation(self.program, "pos")
        tex0_location = bgl.glGetAttribLocation(self.program, "tex0")

        bgl.glUniform1i(tex0_location, 0)

        bgl.glEnableVertexAttribArray(texturecoord_location)
        bgl.glEnableVertexAttribArray(position_location)

        # Generate geometry buffers for drawing textured quad
        width, height = dimensions
        position = [0.0, 0.0, width, 0.0, width, height, 0.0, height]
        position = bgl.Buffer(bgl.GL_FLOAT, len(position), position)
        texcoord = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]
        texcoord = bgl.Buffer(bgl.GL_FLOAT, len(texcoord), texcoord)

        self.vertex_buffer = bgl.Buffer(bgl.GL_INT, 2)

        bgl.glGenBuffers(2, self.vertex_buffer)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vertex_buffer[0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER, 32, position, bgl.GL_STATIC_DRAW)
        bgl.glVertexAttribPointer(position_location, 2, bgl.GL_FLOAT,
                                  bgl.GL_FALSE, 0, None)

        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vertex_buffer[1])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER, 32, texcoord, bgl.GL_STATIC_DRAW)
        bgl.glVertexAttribPointer(texturecoord_location, 2, bgl.GL_FLOAT,
                                  bgl.GL_FALSE, 0, None)

        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, 0)
        bgl.glBindVertexArray(0)