Example #1
0
    def draw_texture(x=0, y=0, w=30, h=10, texname=texname):
        # function to draw a texture
        bgl.glDisable(bgl.GL_DEPTH_TEST)

        act_tex = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_TEXTURE_2D, act_tex)

        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_REPLACE)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, texname)

        texco = [(0, 1), (1, 1), (1, 0), (0, 0)]
        verco = [(x, y), (x + w, y), (x + w, y - h), (x, y - h)]

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

        # restoring settings
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, act_tex[0])
        bgl.glDisable(bgl.GL_TEXTURE_2D)
def crosshairs():
    """
    Show crosshais in Manipulation Mode
    Use the OpenGL-Wrapper to draw the image
    """

    imageHeight = windowHeight * 0.05
    imageWidth = imageHeight

    x = windowWidth * 0.5 - imageWidth / 2
    y = windowHeight * 0.5 - imageHeight / 2

    gl_position = [[x, y], [x + imageWidth, y],
                   [x + imageWidth, y + imageHeight], [x, y + imageHeight]]

    view_buf = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
    view = view_buf.to_list() if hasattr(view_buf,
                                         "to_list") else view_buf.list
    # Save the state
    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)
    # Disable depth test so we always draw over things
    bgl.glDisable(bgl.GL_DEPTH_TEST)
    # Disable lighting so everything is shadless
    bgl.glDisable(bgl.GL_LIGHTING)
    # Unbinding the texture prevents BGUI frames from somehow picking up on
    # color of the last used texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
    # Make sure we're using smooth shading instead of flat
    bgl.glShadeModel(bgl.GL_SMOOTH)
    # Setup the matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, view[2], 0, view[3])
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()

    bgl.glEnable(bgl.GL_TEXTURE_2D)
    # Enable alpha blending
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    # Bind the texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, crosshairs_id)
    # Draw the textured quad
    bgl.glColor4f(1, 1, 1, 1)
    bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
    bgl.glPolygonOffset(1.0, 1.0)
    bgl.glBegin(bgl.GL_QUADS)
    for i in range(4):
        bgl.glTexCoord2f(texco[i][0], texco[i][1])
        bgl.glVertex2f(gl_position[i][0], gl_position[i][1])
    bgl.glEnd()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
    bgl.glPopAttrib()
Example #3
0
def screenshot(x, y, w, h, mode=bgl.GL_FRONT, type=bgl.GL_BYTE):
    """スクリーンショットを撮ってRGBAのfloatバッファを返す
    :param x: Window.x
    :type x: int
    :param y: Window.y
    :type y: int
    :param w: Window.width
    :type w: int
    :param h: Window.height
    :type h: int
    :param mode: 読み込み先
    :type mode: int
    :param type: バッファの型。bgl.GL_BYTE, bgl.GL_INT, ...
    :type type: int
    :return: スクリーンショット。float RGBA
    :rtype: bgl.Buffer
    """
    buf = bgl.Buffer(type, w * h * 4)
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    bgl.glReadBuffer(mode)
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, type, buf)
    bgl.glFinish()
    bgl.glReadBuffer(mode_bak[0])
    return buf
    def refresh_font_texture(self):
        # save texture state
        buf = gl.Buffer(gl.GL_INT, 1)
        gl.glGetIntegerv(gl.GL_TEXTURE_BINDING_2D, buf)
        last_texture = buf[0]

        width, height, pixels = self.io.fonts.get_tex_data_as_rgba32()

        if self._font_texture is not None:
            gl.glDeleteTextures([self._font_texture])

        gl.glGenTextures(1, buf)
        self._font_texture = buf[0]

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

        pixel_buffer = gl.Buffer(gl.GL_BYTE, [4 * width * height])
        pixel_buffer[:] = pixels
        gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0,
                        gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, pixel_buffer)

        self.io.fonts.texture_id = self._font_texture
        gl.glBindTexture(gl.GL_TEXTURE_2D, last_texture)
        self.io.fonts.clear_tex_data()
Example #5
0
    def draw(self, context):
        self.draw_area_context = context
        if self.event is not None:
            # Use OpenGL to get the size of the region we can draw without overlapping with other areas
            mybuffer = bgl.Buffer(bgl.GL_INT, 4)
            bgl.glGetIntegerv(bgl.GL_VIEWPORT, mybuffer)
            mx = self.event.mouse_region_x
            my = self.event.mouse_region_y
            mabx = self.mouse_position_absolute[0]
            maby = self.mouse_position_absolute[1]
            self.mouse_cursor_inside = (
                    (mabx > mybuffer[0]) and (mabx < (mybuffer[0] + mybuffer[2])) and (
                    maby > mybuffer[1]) and (maby < (mybuffer[1] + mybuffer[3])))

            # if auto_hide is enabled , draw my Morphs ONLY if the mouse is located inside the area
            # that draws at the time
            if (
                    self.mouse_cursor_inside and self.auto_hide and context.area.type == "VIEW_3D" and context.region.type == "WINDOW") or not self.auto_hide:
                self.draw_area_context = context
                self.draw_area = mybuffer

                # from that extract information about the region and
                # assign it to relevant instance variables
                self.draw_area_position = [mybuffer[0], mybuffer[1]]
                self.draw_area_width = mybuffer[2]
                self.draw_area_height = mybuffer[3]

                self.mouse_position = [self.mouse_position_absolute[0] - self.draw_area[0],
                                       self.mouse_position_absolute[1] - self.draw_area[1]]

                self.mOpenGLCanvas.draw()
Example #6
0
def window_space(win):
    modelview_mat = bgl.Buffer(bgl.GL_DOUBLE, 16)
    projection_mat = bgl.Buffer(bgl.GL_DOUBLE, 16)
    bgl.glGetDoublev(bgl.GL_MODELVIEW_MATRIX, modelview_mat)
    bgl.glGetDoublev(bgl.GL_PROJECTION_MATRIX, projection_mat)

    matrix_mode = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, matrix_mode)

    viewport = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport)

    bgl.glViewport(0, 0, win.width, win.height)
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    ofs = -0.01
    bgl.glOrtho(ofs, win.width + ofs, ofs, win.height + ofs, -100, 100)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    bgl.glMatrixMode(matrix_mode[0])

    yield

    bgl.glViewport(*viewport)

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadMatrixd(projection_mat)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadMatrixd(modelview_mat)
    bgl.glMatrixMode(matrix_mode[0])
Example #7
0
def draw_texture(x, y, w, h, texture, mode=None):
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_DRAW_BUFFER, mode_bak)
    if mode is not None:
        bgl.glDrawBuffer(mode)

    bgl.glEnable(bgl.GL_TEXTURE_2D)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture)

    bgl.glColor4d(1.0, 1.0, 1.0, 1.0)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glTexCoord2d(0.0, 0.0)
    bgl.glVertex2i(x, y)
    bgl.glTexCoord2d(1.0, 0.0)
    bgl.glVertex2i(x + w, y)
    bgl.glTexCoord2d(1.0, 1.0)
    bgl.glVertex2i(x + w, y + h)
    bgl.glTexCoord2d(0.0, 1.0)
    bgl.glVertex2i(x, y + h)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_TEXTURE_2D)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    if mode is not None:
        bgl.glDrawBuffer(mode_bak[0])
Example #8
0
def screenshot(x, y, w, h, mode=bgl.GL_FRONT, type=bgl.GL_BYTE):
    """スクリーンショットを撮ってRGBAのfloatバッファを返す
    :param x: Window.x
    :type x: int
    :param y: Window.y
    :type y: int
    :param w: Window.width
    :type w: int
    :param h: Window.height
    :type h: int
    :param mode: 読み込み先
    :type mode: int
    :param type: バッファの型。bgl.GL_BYTE, bgl.GL_INT, ...
    :type type: int
    :return: スクリーンショット。float RGBA
    :rtype: bgl.Buffer
    """
    buf = bgl.Buffer(type, w * h * 4)
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    bgl.glReadBuffer(mode)
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, type, buf)
    bgl.glFinish()
    bgl.glReadBuffer(mode_bak[0])
    return buf
Example #9
0
def draw_texture(x, y, w, h, texture, mode=None):
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_DRAW_BUFFER, mode_bak)
    if mode is not None:
        bgl.glDrawBuffer(mode)

    bgl.glEnable(bgl.GL_TEXTURE_2D)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture)

    bgl.glColor4d(1.0, 1.0, 1.0, 1.0)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glTexCoord2d(0.0, 0.0)
    bgl.glVertex2i(x, y)
    bgl.glTexCoord2d(1.0, 0.0)
    bgl.glVertex2i(x + w, y)
    bgl.glTexCoord2d(1.0, 1.0)
    bgl.glVertex2i(x + w, y + h)
    bgl.glTexCoord2d(0.0, 1.0)
    bgl.glVertex2i(x, y + h)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_TEXTURE_2D)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    if mode is not None:
        bgl.glDrawBuffer(mode_bak[0])
Example #10
0
    def update_placement(self, do_update):
        if not do_update and perf_counter() > (self.last_update + 0.25):
            return

        viewport_info = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)

        width = viewport_info[2]
        height = viewport_info[3]

        x_offset = 0
        y_offset = 0

        region, area = self.find_region(width, height)
        if region:
            for region in area.regions:
                if region.type == 'TOOLS':
                    x_offset = region.width
                if region.type == 'HEADER':
                    y_offset = region.height
                if region.type == 'TOOL_HEADER':
                    y_offset = region.height

        self.x = x_offset + 18
        self.y = height - y_offset - 60
        self.last_update = perf_counter()
Example #11
0
    def draw_texture(x=0, y=0, w=30, h=10, texname=texname):
        # function to draw a texture
        bgl.glDisable(bgl.GL_DEPTH_TEST)

        act_tex = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_TEXTURE_2D, act_tex)

        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE,
                      bgl.GL_REPLACE)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, texname)

        texco = [(0, 1), (1, 1), (1, 0), (0, 0)]
        verco = [(x, y), (x + w, y), (x + w, y - h), (x, y - h)]

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

        # restoring settings
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, act_tex[0])
        bgl.glDisable(bgl.GL_TEXTURE_2D)
Example #12
0
def window_space(win):
    modelview_mat = bgl.Buffer(bgl.GL_DOUBLE, 16)
    projection_mat = bgl.Buffer(bgl.GL_DOUBLE, 16)
    bgl.glGetDoublev(bgl.GL_MODELVIEW_MATRIX, modelview_mat)
    bgl.glGetDoublev(bgl.GL_PROJECTION_MATRIX, projection_mat)

    matrix_mode = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, matrix_mode)

    viewport = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport)

    bgl.glViewport(0, 0, win.width, win.height)
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    ofs = -0.01
    bgl.glOrtho(ofs, win.width + ofs, ofs, win.height + ofs, -100, 100)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    bgl.glMatrixMode(matrix_mode[0])

    yield

    bgl.glViewport(*viewport)

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadMatrixd(projection_mat)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadMatrixd(modelview_mat)
    bgl.glMatrixMode(matrix_mode[0])
Example #13
0
    def __init__(self, context):
        rv3d = context.region_data
        persmat = rv3d.perspective_matrix
        flatten_persmat = [persmat[i][j] for i in range(4) for j in range(4)]
        self.persmat_buffer = bgl.Buffer(bgl.GL_FLOAT, 16, flatten_persmat)

        # GL_BLEND
        blend = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend)
        self.blend = blend[0]

        # GL_COLOR
        color = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, color)
        self.color = color

        # GL_LINE_WIDTH
        line_width = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, line_width)
        self.line_width = line_width[0]

        # GL_Matrix_MODE
        matrix_mode = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, matrix_mode)
        self.matrix_mode = matrix_mode[0]

        # GL_PROJECTION_MATRIX
        projection_matrix = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, projection_matrix)
        self.projection_matrix = projection_matrix

        # blf: size, dpi
        self.size_dpi = (11, context.user_preferences.system.dpi)
    def __init__(self, dimensions):
        # Generate dummy float image buffer
        self.dimensions = dimensions
        width, height = dimensions

        pixels = [1, 0.2, 0.1, 1.0] * width * height
        pixels = bgl.Buffer(bgl.GL_FLOAT, width * height * 4, 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_FLOAT, 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)

        # Bind shader that converts from scene linear to display space,
        # use the scene's color management settings.
        shader_program = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, shader_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(
            shader_program[0], "texCoord")
        position_location = bgl.glGetAttribLocation(shader_program[0], "pos")

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

        # Generate geometry buffers for drawing textured quad
        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)
Example #15
0
def crosshairs():
    """
    Show crosshais in Manipulation Mode
    Use the OpenGL-Wrapper to draw the image
    """
    
    imageHeight = windowHeight * 0.05
    imageWidth = imageHeight

    x = windowWidth * 0.5 - imageWidth/2
    y = windowHeight * 0.5 - imageHeight/2
    
    gl_position = [[x, y],[x+imageWidth, y],[x+imageWidth, y+imageHeight],[x, y+imageHeight]]
    
    view_buf = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
    view = view_buf.to_list() if hasattr(view_buf, "to_list") else view_buf.list
    # Save the state
    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)      
    # Disable depth test so we always draw over things
    bgl.glDisable(bgl.GL_DEPTH_TEST)   
    # Disable lighting so everything is shadless
    bgl.glDisable(bgl.GL_LIGHTING)   
    # Unbinding the texture prevents BGUI frames from somehow picking up on
    # color of the last used texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)      
    # Make sure we're using smooth shading instead of flat
    bgl.glShadeModel(bgl.GL_SMOOTH)
    # Setup the matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, view[2], 0, view[3])
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    
    bgl.glEnable(bgl.GL_TEXTURE_2D)
    # Enable alpha blending
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    # Bind the texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, crosshairs_id)
    # Draw the textured quad
    bgl.glColor4f(1, 1, 1, 1)
    bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
    bgl.glPolygonOffset(1.0, 1.0)
    bgl.glBegin(bgl.GL_QUADS)
    for i in range(4):
       bgl.glTexCoord2f(texco[i][0], texco[i][1])
       bgl.glVertex2f(gl_position[i][0], gl_position[i][1])
    bgl.glEnd()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
    bgl.glPopAttrib()
Example #16
0
    def bind(self):
        if self is not _SnapOffscreen.bound:
            if _SnapOffscreen.bound is None:
                bgl.glGetIntegerv(bgl.GL_FRAMEBUFFER_BINDING, self.cur_fbo)
                bgl.glGetIntegerv(bgl.GL_VIEWPORT, self.cur_viewport)

            bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.fbo[0])
            bgl.glViewport(0, 0, self.width, self.height)
            _SnapOffscreen.bound = self
Example #17
0
    def bind(self):
        if self is not _SnapOffscreen.bound:
            if _SnapOffscreen.bound is None:
                bgl.glGetIntegerv(bgl.GL_FRAMEBUFFER_BINDING, self.cur_fbo)
                bgl.glGetIntegerv(bgl.GL_VIEWPORT, self.cur_viewport)

            bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.fbo[0])
            bgl.glViewport(0, 0, self.width, self.height)
            _SnapOffscreen.bound = self
Example #18
0
 def _backup_integers(self, *keys_and_lengths):
     """Helper to back up opengl state"""
     keys = keys_and_lengths[::2]
     lengths = keys_and_lengths[1::2]
     buf = gl.Buffer(gl.GL_INT, max(lengths))
     values = []
     for k, n in zip(keys, lengths):
         gl.glGetIntegerv(k, buf)
         values.append(buf[0] if n == 1 else buf[:n])
     return values
    def _draw_texture(texture_id, x, y, width, height):
        # INITIALIZATION

        # Getting shader program
        shader_program = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, shader_program)

        # Generate vertex array
        vertex_array = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGenVertexArrays(1, vertex_array)

        texturecoord_location = bgl.glGetAttribLocation(
            shader_program[0], "texCoord")
        position_location = bgl.glGetAttribLocation(shader_program[0], "pos")

        # Generate geometry buffers for drawing textured quad
        position = [x, y, x + width, y, x + width, y + height, x, y + 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)

        vertex_buffer = bgl.Buffer(bgl.GL_INT, 2)
        bgl.glGenBuffers(2, vertex_buffer)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, vertex_buffer[0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER, 32, position, bgl.GL_STATIC_DRAW)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, vertex_buffer[1])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER, 32, texcoord, bgl.GL_STATIC_DRAW)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, 0)

        # DRAWING
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture_id)

        bgl.glBindVertexArray(vertex_array[0])
        bgl.glEnableVertexAttribArray(texturecoord_location)
        bgl.glEnableVertexAttribArray(position_location)

        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, vertex_buffer[0])
        bgl.glVertexAttribPointer(position_location, 2, bgl.GL_FLOAT,
                                  bgl.GL_FALSE, 0, None)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, vertex_buffer[1])
        bgl.glVertexAttribPointer(texturecoord_location, 2, bgl.GL_FLOAT,
                                  bgl.GL_FALSE, 0, None)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, 0)

        bgl.glDrawArrays(bgl.GL_TRIANGLE_FAN, 0, 4)

        bgl.glBindVertexArray(0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

        # DELETING
        bgl.glDeleteBuffers(2, vertex_buffer)
        bgl.glDeleteVertexArrays(1, vertex_array)
Example #20
0
    def __init__(self, dimensions):
        # Generate dummy float image buffer
        self.dimensions = dimensions
        width, height = dimensions

        pixels = [0.1, 0.2, 0.1, 1.0] * width * height
        pixels = bgl.Buffer(bgl.GL_FLOAT, width * height * 4, 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_FLOAT, 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)

        # Bind shader that converts from scene linear to display space,
        # use the scene's color management settings.
        shader_program = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, shader_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(shader_program[0], "texCoord");
        position_location = bgl.glGetAttribLocation(shader_program[0], "pos");

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

        # Generate geometry buffers for drawing textured quad
        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)
Example #21
0
    def __init__(self, dimensions):
        self.dimensions = dimensions
        width, height = dimensions

        pixels = [0.1, 0.2, 0.1, 1.0] * width * height
        pixels = bgl.Buffer(bgl.GL_FLOAT, width * height * 4, pixels)

        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_FLOAT, pixels)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER,
                            bgl.GL_LINEAR)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

        shader_program = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, shader_program)

        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(
            shader_program[0], "texCoord")
        position_location = bgl.glGetAttribLocation(shader_program[0], "pos")

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

        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)
Example #22
0
    def _init_opengl(self, engine, scene):
        # Create texture
        self.texture = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGenTextures(1, self.texture)
        self.texture_id = self.texture[0]

        # Bind shader that converts from scene linear to display space,
        # use the scene's color management settings.
        engine.bind_display_space_shader(scene)
        shader_program = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, shader_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(
            shader_program[0], "texCoord")
        position_location = bgl.glGetAttribLocation(shader_program[0], "pos")

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

        # Generate geometry buffers for drawing textured quad
        width = self._width * self._pixel_size
        height = self._height * self._pixel_size
        position = [
            self._offset_x, self._offset_y, self._offset_x + width,
            self._offset_y, self._offset_x + width, self._offset_y + height,
            self._offset_x, self._offset_y + 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, NULL)
        bgl.glBindVertexArray(NULL)
        engine.unbind_display_space_shader()
def color_placing():
    """
    Draw the green rectangle via OpenGL-Wrapper
    """
    imageHeight = windowHeight * 0.05
    imageWidth = imageHeight

    x = windowWidth * 0.5 - imageWidth / 2
    y = windowHeight * 0.5 - imageHeight / 2

    gl_position = [[x, y], [x + imageWidth, y],
                   [x + imageWidth, y + imageHeight], [x, y + imageHeight]]

    view_buf = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
    view = view_buf.to_list() if hasattr(view_buf,
                                         "to_list") else view_buf.list
    # Save the state
    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)
    # Disable depth test so we always draw over things
    bgl.glDisable(bgl.GL_DEPTH_TEST)
    # Disable lighting so everything is shadless
    bgl.glDisable(bgl.GL_LIGHTING)
    # Make sure we're using smooth shading instead of flat
    bgl.glShadeModel(bgl.GL_SMOOTH)
    # Setup the matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, view[2], 0, view[3])
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()

    # Enable alpha blending
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    # Draw the colored quad
    bgl.glColor4f(0, 1, 0, 0.25)
    bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
    bgl.glPolygonOffset(1.0, 1.0)
    bgl.glBegin(bgl.GL_QUADS)
    for i in range(4):
        bgl.glTexCoord2f(texco[i][0], texco[i][1])
        bgl.glVertex2f(gl_position[i][0], gl_position[i][1])
    bgl.glEnd()

    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
    bgl.glPopAttrib()
def cursor_handler(context):

	global ticks
	global buf
	global analog

	bgl.glGetIntegerv(bgl.GL_VIEWPORT,buf)
	width = buf[2]

	t = localtime()
	m = t[4]
	h = (t[3]%12) + m/60.0  # fractional hours
	twopi = 6.283

	# draw text
	font_id = 0
	blf.position(font_id, width - 100, 15, 0)
	blf.size(font_id, 12, 72)  # 12pt text at 72dpi screen
	blf.draw(font_id, strftime("%H:%M:%S", t))

	if analog:
		# also see: https://blog.michelanders.nl/2019/02/working-with-new-opengl-functionality.html
		# 50% alpha, 2 pixel lines
		bgl.glEnable(bgl.GL_BLEND)
		bgl.glLineWidth(2)

		points = []
		# draw a clock in the lower right hand corner
		startx, starty = (width - 22.0,22.0)
		smallhandx, smallhandy = (startx + 9*sin(twopi * h/12),
								starty + 9*cos(twopi * h/12))
		bighandx, bighandy = (startx + 15*sin(twopi * m/60),
								starty + 15*cos(twopi * m/60))
		points.append((startx, starty))
		points.append((bighandx, bighandy))
		points.append((startx, starty))
		points.append((smallhandx, smallhandy))
		# twelve small dots
		for x,y in ticks:
			points.append((startx + 17*x, starty + 17*y))
			points.append((startx + 18*x, starty + 18*y))

		shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
		batch = batch_for_shader(shader, 'LINES', {"pos": points})
		shader.bind()
		shader.uniform_float("color", (1.0, 1.0, 1.0, 0.5))
		batch.draw(shader)
	  
		# restore opengl defaults
		bgl.glLineWidth(1)
		bgl.glDisable(bgl.GL_BLEND)
 def _get(self, instance, owner):
     glGetIntegerv(GL_BLEND_SRC_RGB, int1buf0)
     glGetIntegerv(GL_BLEND_DST_RGB, int1buf1)
     glGetIntegerv(GL_BLEND_SRC_ALPHA, int1buf2)
     glGetIntegerv(GL_BLEND_DST_ALPHA, int1buf3)
     return BlendFuncSeparate(blend_funcs_v2k[int1buf0[0]], blend_funcs_v2k[int1buf1[0]],
                              blend_funcs_v2k[int1buf2[0]], blend_funcs_v2k[int1buf3[0]])
Example #26
0
def color_placing():
    """
    Draw the green rectangle via OpenGL-Wrapper
    """
    imageHeight = windowHeight * 0.05
    imageWidth = imageHeight

    x = windowWidth * 0.5 - imageWidth/2
    y = windowHeight * 0.5 - imageHeight/2
    
    gl_position = [[x, y],[x+imageWidth, y],[x+imageWidth, y+imageHeight],[x, y+imageHeight]]
    
    view_buf = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
    view = view_buf.to_list() if hasattr(view_buf, "to_list") else view_buf.list
    # Save the state
    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)      
    # Disable depth test so we always draw over things
    bgl.glDisable(bgl.GL_DEPTH_TEST)   
    # Disable lighting so everything is shadless
    bgl.glDisable(bgl.GL_LIGHTING)   
    # Make sure we're using smooth shading instead of flat
    bgl.glShadeModel(bgl.GL_SMOOTH)
    # Setup the matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, view[2], 0, view[3])
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    
    
    # Enable alpha blending
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    # Draw the colored quad
    bgl.glColor4f(0, 1, 0, 0.25)
    bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
    bgl.glPolygonOffset(1.0, 1.0)
    bgl.glBegin(bgl.GL_QUADS)
    for i in range(4):
       bgl.glTexCoord2f(texco[i][0], texco[i][1])
       bgl.glVertex2f(gl_position[i][0], gl_position[i][1])
    bgl.glEnd()

    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
    bgl.glPopAttrib()
Example #27
0
    def __init__(self, width, height):
        import ctypes

        self.freed = False
        self.is_bound = False

        self.width = width
        self.height = height

        self.fbo = bgl.Buffer(bgl.GL_INT, 1)
        self.buf_color = bgl.Buffer(bgl.GL_INT, 1)
        self.buf_depth = bgl.Buffer(bgl.GL_INT, 1)

        self.cur_fbo = bgl.Buffer(bgl.GL_INT, 1)
        self.cur_viewport = bgl.Buffer(bgl.GL_INT, 4)

        bgl.glGenRenderbuffers(1, self.buf_depth)
        bgl.glBindRenderbuffer(bgl.GL_RENDERBUFFER, self.buf_depth[0])
        bgl.glRenderbufferStorage(bgl.GL_RENDERBUFFER, bgl.GL_DEPTH_COMPONENT,
                                  width, height)

        bgl.glGenTextures(1, self.buf_color)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.buf_color[0])
        NULL = bgl.Buffer(bgl.GL_INT, 1, (ctypes.c_int32 * 1).from_address(0))
        bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_R32UI, width, height, 0,
                         bgl.GL_RED_INTEGER, bgl.GL_UNSIGNED_INT, NULL)
        del NULL
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER,
                            bgl.GL_NEAREST)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            bgl.GL_NEAREST)

        bgl.glGetIntegerv(bgl.GL_FRAMEBUFFER_BINDING, self.cur_fbo)

        bgl.glGenFramebuffers(1, self.fbo)
        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.fbo[0])
        bgl.glFramebufferRenderbuffer(bgl.GL_FRAMEBUFFER,
                                      bgl.GL_DEPTH_ATTACHMENT,
                                      bgl.GL_RENDERBUFFER, self.buf_depth[0])
        bgl.glFramebufferTexture(bgl.GL_FRAMEBUFFER, bgl.GL_COLOR_ATTACHMENT0,
                                 self.buf_color[0], 0)

        bgl.glDrawBuffers(
            1, bgl.Buffer(bgl.GL_INT, 1, [bgl.GL_COLOR_ATTACHMENT0]))

        status = bgl.glCheckFramebufferStatus(bgl.GL_FRAMEBUFFER)
        if status != bgl.GL_FRAMEBUFFER_COMPLETE:
            print("Framebuffer Invalid", status)

        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.cur_fbo[0])
Example #28
0
    def get_image(self):
        """
        sends serialized image, uint8 image

        """
        _buffer = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_VIEWPORT, _buffer)
        bgl.glReadBuffer(bgl.GL_FRONT)
        pix = bgl.Buffer(bgl.GL_INT, _buffer[2] * _buffer[3])
        bgl.glReadPixels(_buffer[0], _buffer[1], _buffer[2], _buffer[3], bgl.GL_LUMINANCE, bgl.GL_INT, pix)
        array = numpy.zeros((self.screen_w * self.screen_h), dtype=numpy.uint8)
        array[0:self.screen_w * self.screen_h] = pix
        self.get_data((self.screen_w, self.screen_h))
        for i in range(0, len(array), 400):
            self.get_data(array[i:i + 400])
Example #29
0
def h_clip_begin(bounds, padding=[0, 0, 0, 0]):
    vp = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, vp)
    
    B = [bounds[0]+padding[0], bounds[1]+padding[1], bounds[2]-padding[2]*2, bounds[3]-padding[3]*2]
    
    # Do some math to invert the coords
    scp = [0, 0, int(B[2]), int(B[3])]
    scp[0] = int(B[0] + vp[0])
    scp[1] = int(vp[1] + (vp[3] - B[1] - B[3]))
    
    bgl.glEnable(bgl.GL_SCISSOR_TEST)
    bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
    bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_SCISSOR_BIT)
    bgl.glScissor(*scp)
Example #30
0
    def start(context):
        assert not ScissorStack.started

        rgn = context.region
        ScissorStack.context = context
        ScissorStack.box = (rgn.x, rgn.y, rgn.width, rgn.height)

        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, ScissorStack.buf)
        ScissorStack.scissor_enabled = (bgl.glIsEnabled(bgl.GL_SCISSOR_TEST) == bgl.GL_TRUE)
        ScissorStack.stack = [tuple(ScissorStack.buf)]

        ScissorStack.started = True

        if not ScissorStack.scissor_enabled:
            bgl.glEnable(bgl.GL_SCISSOR_TEST)
Example #31
0
    def start(context):
        assert not ScissorStack.started

        rgn = context.region
        ScissorStack.context = context
        ScissorStack.box = (rgn.x, rgn.y, rgn.width, rgn.height)

        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, ScissorStack.buf)
        ScissorStack.scissor_enabled = (bgl.glIsEnabled(bgl.GL_SCISSOR_TEST) == bgl.GL_TRUE)
        ScissorStack.stack = [tuple(ScissorStack.buf)]

        ScissorStack.started = True

        if not ScissorStack.scissor_enabled:
            bgl.glEnable(bgl.GL_SCISSOR_TEST)
Example #32
0
    def init_opengl(self, engine, scene):
        self.texture = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGenTextures(1, self.texture)

        self.generate_texture()

        engine.bind_display_space_shader(scene)

        shader_program = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, shader_program)

        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(
            shader_program[0], "texCoord")
        position_location = bgl.glGetAttribLocation(shader_program[0], "pos")

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

        position = [
            0.0, 0.0, self.width, 0.0, self.width, self.height, 0.0,
            self.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)

        engine.unbind_display_space_shader()
Example #33
0
def cursor_handler(context):

	global ticks
	global buf

	if context.scene.show_clock:
		bgl.glGetIntegerv(bgl.GL_VIEWPORT,buf)
		width = buf[2]

		t = localtime()
		m = t[4]
		h = (t[3]%12) + m/60.0  # fractional hours
		twopi = 6.283

		if context.scene.clock_analog:
			# 50% alpha, 2 pixel lines
			bgl.glEnable(bgl.GL_BLEND)
			bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
			bgl.glLineWidth(2)

			# draw a clock in the lower right hand corner
			startx, starty = (width - 22.0,22.0)
			smallhandx, smallhandy = (startx + 9*sin(twopi * h/12),
									starty + 9*cos(twopi * h/12))
			bighandx, bighandy = (startx + 15*sin(twopi * m/60),
									starty + 15*cos(twopi * m/60))
			bgl.glBegin(bgl.GL_LINES)
			bgl.glVertex2f(startx, starty)
			bgl.glVertex2f(bighandx, bighandy)
			bgl.glVertex2f(startx, starty)
			bgl.glVertex2f(smallhandx, smallhandy)
			# twelve small dots
			for x,y in ticks:
				bgl.glVertex2f(startx + 17*x, starty + 17*y)
				bgl.glVertex2f(startx + 18*x, starty + 18*y)
			bgl.glEnd()

			# restore opengl defaults
			bgl.glLineWidth(1)
			bgl.glDisable(bgl.GL_BLEND)
			bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
		else:
			# draw text
			font_id = 0
			blf.position(font_id, width - 70, 15, 0)
			blf.size(font_id, 12, 72)  # 12pt text at 72dpi screen
			blf.draw(font_id, strftime("%H:%M:%S", t))
Example #34
0
def draw_callback_px(self, context):
    
    #get RegionView3D
    r3d = 0
    for space in context.area.spaces:
        if space.type == 'VIEW_3D':
            r3d = space.region_3d
    
    if r3d == 0:
        print("region_3D NOT FOUND")
        pass
    
    screenWidth = context.area.width
    screenHeight = context.area.height
    
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
    
    # get old viewport properties
    oldViewport = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, oldViewport) 
    
    #oldViewDistance = r3d.view_distance
    
    oldMatrix = bgl.Buffer(bgl.GL_DOUBLE, [4,4])
    bgl.glGetDoublev(bgl.GL_PROJECTION_MATRIX, oldMatrix)
    
    viewportWidth = int(oldViewport[2]/4)
    viewportHeight = int(oldViewport[3]/4)
    
    #bgl.glViewport(screenWidth - viewportWidth, screenHeight - viewportHeight, viewportWidth, viewportHeight)
    bgl.glViewport(screenWidth - viewportWidth, (screenHeight - viewportHeight) + int((viewportHeight-viewportWidth)/2), viewportWidth, viewportHeight)
    
    draw_cube(context, r3d)

    # restore opengl defaults
    #r3d.view_distance = oldViewDistance
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_DEPTH_TEST)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    bgl.glViewport(oldViewport[0],oldViewport[1],oldViewport[2],oldViewport[3])
    
    bgl.glPushMatrix()
    bgl.glLoadMatrixf(oldMatrix)
    bgl.glPopMatrix()
Example #35
0
File: zu.py Project: vktec/zu
    def prepare_viewport(self, ctx, dg):
        width, height = ctx.region.width, ctx.region.height
        self.dim = (width, height)

        buf = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_DRAW_FRAMEBUFFER_BINDING, buf)
        fb = buf[0]

        self.genfb(width, height)

        bgl.glGenVertexArrays(1, buf)
        self.vao = buf[0]
        bgl.glBindVertexArray(self.vao)

        quad = bgl.Buffer(bgl.GL_FLOAT, 2 * 4,
                          [0, 0, width, 0, width, height, 0, height])
        uv = bgl.Buffer(bgl.GL_FLOAT, 2 * 4, [0, 0, 1, 0, 1, 1, 0, 1])

        self.bind_display_space_shader(dg.scene)
        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, buf)
        self.unbind_display_space_shader()
        self.quad_in = bgl.glGetAttribLocation(buf[0], "pos")
        self.uv_in = bgl.glGetAttribLocation(buf[0], "texCoord")

        bgl.glEnableVertexAttribArray(self.quad_in)
        bgl.glEnableVertexAttribArray(self.uv_in)

        self.vtx_buf = bgl.Buffer(bgl.GL_INT, 2)
        bgl.glGenBuffers(2, self.vtx_buf)
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vtx_buf[0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER, 2 * 4 * 4, quad,
                         bgl.GL_STATIC_DRAW)
        bgl.glVertexAttribPointer(self.quad_in, 2, bgl.GL_FLOAT, bgl.GL_FALSE,
                                  0, None)

        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, self.vtx_buf[1])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER, 2 * 4 * 4, uv,
                         bgl.GL_STATIC_DRAW)
        bgl.glVertexAttribPointer(self.uv_in, 2, bgl.GL_FLOAT, bgl.GL_FALSE, 0,
                                  None)

        bgl.glDisableVertexAttribArray(self.quad_in)
        bgl.glDisableVertexAttribArray(self.uv_in)

        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, fb)
Example #36
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 #37
0
    def __init__(self, width, height):
        self.freed = False
        self.is_bound = False

        self.width = width
        self.height = height

        self.fbo = bgl.Buffer(bgl.GL_INT, 1)
        self.buf_color = bgl.Buffer(bgl.GL_INT, 1)
        self.buf_depth = bgl.Buffer(bgl.GL_INT, 1)

        self.cur_fbo = bgl.Buffer(bgl.GL_INT, 1)
        self.cur_viewport = bgl.Buffer(bgl.GL_INT, 4)

        bgl.glGenRenderbuffers(1, self.buf_depth)
        bgl.glGenTextures(1, self.buf_color)
        self._config_textures()

        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER,
                            bgl.GL_NEAREST)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            bgl.GL_NEAREST)

        bgl.glGetIntegerv(bgl.GL_FRAMEBUFFER_BINDING, self.cur_fbo)

        bgl.glGenFramebuffers(1, self.fbo)
        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.fbo[0])
        bgl.glFramebufferRenderbuffer(bgl.GL_FRAMEBUFFER,
                                      bgl.GL_DEPTH_ATTACHMENT,
                                      bgl.GL_RENDERBUFFER, self.buf_depth[0])

        bgl.glFramebufferTexture(bgl.GL_FRAMEBUFFER, bgl.GL_COLOR_ATTACHMENT0,
                                 self.buf_color[0], 0)

        bgl.glDrawBuffers(
            1, bgl.Buffer(bgl.GL_INT, 1, [bgl.GL_COLOR_ATTACHMENT0]))

        status = bgl.glCheckFramebufferStatus(bgl.GL_FRAMEBUFFER)
        if status != bgl.GL_FRAMEBUFFER_COMPLETE:
            print("Framebuffer Invalid", status)

        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.cur_fbo[0])
Example #38
0
def draw_fill(color, x, y, size, alpha=1.0, round_radius=0.0, poly_line=None):
    cx = x + size / 2
    cy = y + size / 2

    round_radius = min(size / 2, round_radius)

    gl_blend = bgl.Buffer(bgl.GL_BYTE, 1)
    bgl.glGetIntegerv(bgl.GL_BLEND, gl_blend)
    bgl.glEnable(bgl.GL_BLEND)

    if poly_line is not None:
        coords = [(co[0] - x, co[1] - y) for co in poly_line]
    else:
        r = round_radius
        pi = math.pi
        coords = []  # 0.0 ~ +size の範囲
        # 左下
        coords += vagl.draw_arc_get_vectors(r, r, r, pi, pi * 3 / 2, 4)
        # 右下
        coords += vagl.draw_arc_get_vectors(x + size - r, r, r, pi * 3 / 2,
                                            0.0, 4)
        # 右上
        coords += vagl.draw_arc_get_vectors(x + size - r, y + size - r, r, 0.0,
                                            pi / 2, 4)
        # 左上
        coords += vagl.draw_arc_get_vectors(r, y + size - r, r, pi / 2, pi, 4)

    if len(color) == 3:
        color = list(color) + [1.0]
    color = vagl.thin_color(color, alpha)
    bgl.glColor4f(*color)

    bgl.glBegin(bgl.GL_POLYGON)
    for co in coords:
        bgl.glVertex2f(co[0] + x, co[1] + y)
    bgl.glEnd()

    if not gl_blend[0]:
        bgl.glDisable(bgl.GL_BLEND)

    return True
Example #39
0
File: zu.py Project: vktec/zu
    def view_draw(self, ctx, dg):
        if self.scene is None:
            return

        buf = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_DRAW_FRAMEBUFFER_BINDING, buf)
        if buf[0] == 0:
            return

        width, height = ctx.region.width, ctx.region.height
        if self.dim != (width, height):
            self.delfb()
            self.prepare_viewport(ctx, dg)

        # Render the scene
        bgl.glViewport(0, 0, width, height)
        cam = ctx.region_data.perspective_matrix
        zu.scene_cam(self.scene, mat(cam))
        zu.scene_draw(self.scene, self.fb)

        # Copy the rendered scene to the viewport (through the color space adjustment shader)
        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, buf[0])
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        self.bind_display_space_shader(dg.scene)
        bgl.glBindVertexArray(self.vao)
        bgl.glEnableVertexAttribArray(self.quad_in)
        bgl.glEnableVertexAttribArray(self.uv_in)

        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.tex)
        bgl.glDrawArrays(bgl.GL_TRIANGLE_FAN, 0, 4)

        bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
        bgl.glDisableVertexAttribArray(self.quad_in)
        bgl.glDisableVertexAttribArray(self.uv_in)
        bgl.glBindVertexArray(0)

        self.unbind_display_space_shader()
        bgl.glDisable(bgl.GL_BLEND)
Example #40
0
def draw_fill(color, x, y, size, alpha=1.0, round_radius=0.0):
    cx = x + size / 2
    cy = y + size / 2

    round_radius = min(size / 2, round_radius)

    gl_blend = bgl.Buffer(bgl.GL_BYTE, 1)
    bgl.glGetIntegerv(bgl.GL_BLEND, gl_blend)
    bgl.glEnable(bgl.GL_BLEND)

    r = round_radius
    pi = math.pi
    coords = []  # -size*0.5 ~ +size*0.5 の範囲
    # 左下
    coords += vagl.draw_arc_get_vectors(
        -size / 2 + r, -size / 2 + r, r, pi, pi * 3 / 2, 4)
    # 右下
    coords += vagl.draw_arc_get_vectors(
        size / 2 - r, -size / 2 + r, r, pi * 3 / 2, 0.0, 4)
    # 右上
    coords += vagl.draw_arc_get_vectors(
        size / 2 - r, size / 2 - r, r, 0.0, pi / 2, 4)
    # 左上
    coords += vagl.draw_arc_get_vectors(
        -size / 2 + r, size / 2 - r, r, pi / 2, pi, 4)

    if len(color) == 3:
        color = list(color) + [1.0]
    color = vagl.thin_color(color, alpha)
    bgl.glColor4f(*color)

    bgl.glBegin(bgl.GL_POLYGON)
    for co in coords:
        bgl.glVertex2f(co[0] + cx, co[1] + cy)
    bgl.glEnd()

    if not gl_blend[0]:
        bgl.glDisable(bgl.GL_BLEND)

    return True
Example #41
0
def draw_fill(color, x, y, size, alpha=1.0, round_radius=0.0):
    cx = x + size / 2
    cy = y + size / 2

    round_radius = min(size / 2, round_radius)

    gl_blend = bgl.Buffer(bgl.GL_BYTE, 1)
    bgl.glGetIntegerv(bgl.GL_BLEND, gl_blend)
    bgl.glEnable(bgl.GL_BLEND)

    r = round_radius
    pi = math.pi
    coords = []  # -size*0.5 ~ +size*0.5 の範囲
    # 左下
    coords += vagl.draw_arc_get_vectors(-size / 2 + r, -size / 2 + r, r, pi,
                                        pi * 3 / 2, 4)
    # 右下
    coords += vagl.draw_arc_get_vectors(size / 2 - r, -size / 2 + r, r,
                                        pi * 3 / 2, 0.0, 4)
    # 右上
    coords += vagl.draw_arc_get_vectors(size / 2 - r, size / 2 - r, r, 0.0,
                                        pi / 2, 4)
    # 左上
    coords += vagl.draw_arc_get_vectors(-size / 2 + r, size / 2 - r, r, pi / 2,
                                        pi, 4)

    if len(color) == 3:
        color = list(color) + [1.0]
    color = vagl.thin_color(color, alpha)
    bgl.glColor4f(*color)

    bgl.glBegin(bgl.GL_POLYGON)
    for co in coords:
        bgl.glVertex2f(co[0] + cx, co[1] + cy)
    bgl.glEnd()

    if not gl_blend[0]:
        bgl.glDisable(bgl.GL_BLEND)

    return True
Example #42
0
    def __init__(self, width, height):
        self.freed = False
        self.is_bound = False

        self.width = width
        self.height = height

        self.fbo = bgl.Buffer(bgl.GL_INT, 1)
        self.buf_color = bgl.Buffer(bgl.GL_INT, 1)
        self.buf_depth = bgl.Buffer(bgl.GL_INT, 1)

        self.cur_fbo = bgl.Buffer(bgl.GL_INT, 1)
        self.cur_viewport = bgl.Buffer(bgl.GL_INT, 4)

        bgl.glGenRenderbuffers(1, self.buf_depth)
        bgl.glGenTextures(1, self.buf_color)

        self._config_textures()

        bgl.glGetIntegerv(bgl.GL_FRAMEBUFFER_BINDING, self.cur_fbo)

        bgl.glGenFramebuffers(1, self.fbo)
        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.fbo[0])

        bgl.glFramebufferRenderbuffer(
                bgl.GL_FRAMEBUFFER, bgl.GL_DEPTH_ATTACHMENT,
                bgl.GL_RENDERBUFFER, self.buf_depth[0])

        bgl.glFramebufferTexture(bgl.GL_FRAMEBUFFER, bgl.GL_COLOR_ATTACHMENT0, self.buf_color[0], 0)

        bgl.glDrawBuffers(1, bgl.Buffer(bgl.GL_INT, 1, [bgl.GL_COLOR_ATTACHMENT0]))

        status = bgl.glCheckFramebufferStatus(bgl.GL_FRAMEBUFFER)
        if status != bgl.GL_FRAMEBUFFER_COMPLETE:
            print("Framebuffer Invalid", status)

        bgl.glBindFramebuffer(bgl.GL_FRAMEBUFFER, self.cur_fbo[0])
Example #43
0
def gen_screenshot_texture(x, y, w, h, mode=None):
    scissor_is_enabled = bgl.Buffer(bgl.GL_BYTE, 1)
    bgl.glGetIntegerv(bgl.GL_SCISSOR_TEST, scissor_is_enabled)
    scissor_box = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
    bgl.glEnable(bgl.GL_SCISSOR_TEST)
    bgl.glScissor(x, y, w, h)

    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    if mode is not None:
        bgl.glReadBuffer(mode)

    pixels = bgl.Buffer(bgl.GL_BYTE, 4 * w * h)
    # RGBAにしないと斜めになる
    # GL_UNSIGNED_BYTEでないと色が僅かにずれる
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, pixels)
    bgl.glFinish()

    if mode is not None:
        bgl.glReadBuffer(mode_bak[0])

    # 反転。確認用
    # for i in range(4 * w * h):
    #     if (i % 4) != 3:
    #         pixels[i] = 255 - pixels[i]

    tex = gen_texture()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)
    bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA, w, h, 0, bgl.GL_RGBA,
                     bgl.GL_UNSIGNED_BYTE, pixels)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    if not scissor_is_enabled[0]:
        bgl.glDisable(bgl.GL_SCISSOR_TEST)
    bgl.glScissor(*scissor_box)

    return tex
Example #44
0
	def draw(self):
		cam = bge.logic.getCurrentScene().active_camera
		
		self.position[2] += self.speed
		
		# Get some viewport info
		view_buf = bgl.Buffer(bgl.GL_INT, 4)
		bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
		view = view_buf[:]

		if 0:
			# Save the state
			bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)

			# Disable depth test so we always draw over things
			bgl.glDisable(bgl.GL_DEPTH_TEST)

			# Disable lighting so everything is shadless
			bgl.glDisable(bgl.GL_LIGHTING)

			# Unbinding the texture prevents BGUI frames from somehow picking up on
			# color of the last used texture
			bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

			# Make sure we're using smooth shading instead of flat
			bgl.glShadeModel(bgl.GL_SMOOTH)


		# Calculate x and y
		screen_coord = cam.getScreenPosition(self.position)
		x = screen_coord[0] * ras.getWindowWidth()
		y = ras.getWindowHeight() - (screen_coord[1] * ras.getWindowHeight())
		
		# Check to make sure the position isn't behind the camera
		if not cam.pointInsideFrustum(self.position):
			return
	
		# Calculate scale
		distance = cam.getDistanceTo(self.position)
		if 1000 - distance > 0:
			scale = (1000 - distance) / 1000
		else:
			scale = 0

		# Setup the matrices
		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glPushMatrix()
		bgl.glLoadIdentity()
		bgl.gluOrtho2D(0, view[2], 0, view[3])
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
		bgl.glPushMatrix()
		bgl.glLoadIdentity()
		
		# Center the x
		text_width, text_height = blf.dimensions(self.fontid, self.text)
		x -= text_width / 2

			
		# Draw the font if large enough
		if scale:
			blf.size(self.fontid, int(self.pt_size*scale), 72)
			blf.position(self.fontid, x, y, 0)
			blf.draw(self.fontid, self.text)
			
		# Reset the state
		bgl.glPopMatrix()
		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glPopMatrix()
Example #45
0
def DrawNorth_callback(self, context):

    if not Sun.SP.ShowNorth and North.isActive:
        North.deactivate()
        return

    # ------------------------------------------------------------------
    # Set up the compass needle using the current north offset angle
    # less 90 degrees.  This forces the unit circle to begin at the
    # 12 O'clock instead of 3 O'clock position.
    # ------------------------------------------------------------------
    color = (0.2, 0.6, 1.0, 0.7)
    radius = 100
    angle = -(Sun.NorthOffset - math.pi / 2)
    x = math.cos(angle) * radius
    y = math.sin(angle) * radius

    p1, p2 = (0, 0, 0), (x, y, 0)   # Start & end of needle

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Thanks to Buerbaum Martin for the following which draws openGL
    # lines.  ( From his script space_view3d_panel_measure.py )
    #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ------------------------------------------------------------------
    # Convert the Perspective Matrix of the current view/region.
    # ------------------------------------------------------------------
    view3d = bpy.context
    region = view3d.region_data
    perspMatrix = region.perspective_matrix
    tempMat = [perspMatrix[j][i] for i in range(4) for j in range(4)]
    perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

    # ---------------------------------------------------------
    # Store previous OpenGL settings.
    # ---------------------------------------------------------
    MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
    bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
    MatrixMode_prev = MatrixMode_prev[0]

    # Store projection matrix
    ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
    bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)

    # Store Line width
    lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
    bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
    lineWidth_prev = lineWidth_prev[0]

    # Store GL_BLEND
    blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
    blend_prev = blend_prev[0]

    line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
    line_stipple_prev = line_stipple_prev[0]

    # Store glColor4f
    color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
    bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

    # ---------------------------------------------------------
    # Prepare for 3D drawing
    # ---------------------------------------------------------
    bgl.glLoadIdentity()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadMatrixf(perspBuff)

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_STIPPLE)

    # ------------------
    # and draw the line
    # ------------------
    width = 2
    bgl.glLineWidth(width)
    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex3f(p1[0], p1[1], p1[2])
    bgl.glVertex3f(p2[0], p2[1], p2[2])
    bgl.glEnd()

    # ---------------------------------------------------------
    # Restore previous OpenGL settings
    # ---------------------------------------------------------
    bgl.glLoadIdentity()
    bgl.glMatrixMode(MatrixMode_prev)
    bgl.glLoadMatrixf(ProjMatrix_prev)
    bgl.glLineWidth(lineWidth_prev)

    if not blend_prev:
        bgl.glDisable(bgl.GL_BLEND)
    if not line_stipple_prev:
        bgl.glDisable(bgl.GL_LINE_STIPPLE)

    bgl.glColor4f(color_prev[0],
                  color_prev[1],
                  color_prev[2],
                  color_prev[3])
Example #46
0
    def draw_callback(cls, context):
        prefs = ScreenCastKeysPreferences.get_instance()
        """:type: ScreenCastKeysPreferences"""

        if context.window.as_pointer() != cls.origin['window']:
            return
        rect = cls.calc_draw_rectangle(context)
        if not rect:
            return
        xmin, ymin, xmax, ymax = rect
        win, _area, _region, x, y = cls.get_origin(context)
        w = xmax - x
        h = ymax - y
        if w == h == 0:
            return
        region = context.region
        area = context.area
        if region.type == 'WINDOW':
            r_xmin, r_ymin, r_xmax, r_ymax = region_window_rectangle(area)
        else:
            r_xmin, r_ymin, r_xmax, r_ymax = (
                region.x,
                region.y,
                region.x + region.width - 1,
                region.y + region.height - 1)
        if not intersect_aabb(
                (r_xmin, r_ymin), (r_xmax, r_ymax),
                (xmin + 1, ymin + 1), (xmax - 1, ymax - 1)):
            return

        current_time = time.time()
        draw_any = False

        font_size = prefs.font_size
        font_id = 0
        dpi = context.user_preferences.system.dpi
        blf.size(font_id, font_size, dpi)

        def draw_text(text):
            col = prefs.color_shadow
            bgl.glColor4f(*col[:3], col[3] * 20)
            blf.blur(font_id, 5)
            blf.draw(font_id, text)
            blf.blur(font_id, 0)

            bgl.glColor3f(*prefs.color)
            blf.draw(font_id, text)

        def draw_line(p1, p2):
            bgl.glEnable(bgl.GL_BLEND)
            bgl.glEnable(bgl.GL_LINE_SMOOTH)

            bgl.glLineWidth(3.0)
            bgl.glColor4f(*prefs.color_shadow)
            bgl.glBegin(bgl.GL_LINES)
            bgl.glVertex2f(*p1)
            bgl.glVertex2f(*p2)
            bgl.glEnd()

            bgl.glLineWidth(1.0 if prefs.color_shadow[-1] == 0.0 else 1.5)
            bgl.glColor3f(*prefs.color)
            bgl.glBegin(bgl.GL_LINES)
            bgl.glVertex2f(*p1)
            bgl.glVertex2f(*p2)
            bgl.glEnd()

            bgl.glLineWidth(1.0)
            bgl.glDisable(bgl.GL_LINE_SMOOTH)

        # user_preferences.system.use_region_overlapが真の場合に、
        # 二重に描画されるのを防ぐ
        glscissorbox = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, glscissorbox)
        if context.area.type == 'VIEW_3D' and region.type == 'WINDOW':
            xmin, ymin, xmax, ymax = region_rectangle_v3d(context)
            bgl.glScissor(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)

        th = blf.dimensions(0, string.printable)[1]
        px = x - region.x
        py = y - region.y

        operator_log = cls.removed_old_operator_log()
        if prefs.show_last_operator and operator_log:
            t, name, idname_py, addr = operator_log[-1]
            if current_time - t <= prefs.display_time:
                color = prefs.color
                bgl.glColor3f(*color)

                text = bpy.app.translations.pgettext_iface(name, 'Operator')
                text += " ('{}')".format(idname_py)

                blf.position(font_id, px, py, 0)
                draw_text(text)
                py += th + th * cls.SEPARATOR_HEIGHT * 0.2
                tw = blf.dimensions(font_id, 'Left Mouse')[0]  # 適当
                draw_line((px, py), (px + tw, py))
                py += th * cls.SEPARATOR_HEIGHT * 0.8

                draw_any = True

            else:
                py += th + th * cls.SEPARATOR_HEIGHT

        bgl.glColor3f(*prefs.color)
        if cls.hold_keys or mhm.is_rendering():
            col = prefs.color_shadow[:3] + (prefs.color_shadow[3] * 2,)
            mod_names = cls.sorted_modifiers(cls.hold_keys)
            if mhm.is_rendering():
                if 0:
                    text = '- - -'
                else:
                    text = ''
            else:
                text = ' + '.join(mod_names)
            blf.position(font_id, px, py, 0)
            # blf.draw(font_id, text)
            draw_text(text)
            py += th
            draw_any = True
        else:
            py += th

        event_log = cls.removed_old_event_log()

        if cls.hold_keys or event_log:
            py += th * cls.SEPARATOR_HEIGHT * 0.2
            tw = blf.dimensions(font_id, 'Left Mouse')[0]  # 適当
            draw_line((px, py), (px + tw, py))
            py += th * cls.SEPARATOR_HEIGHT * 0.8
            draw_any = True
        else:
            py += th * cls.SEPARATOR_HEIGHT

        for event_time, event_type, modifiers, count in event_log[::-1]:
            color = prefs.color
            bgl.glColor3f(*color)

            text = event_type.names[event_type.name]
            if modifiers:
                mod_names = cls.sorted_modifiers(modifiers)
                text = ' + '.join(mod_names) + ' + ' + text
            if count > 1:
                text += ' x' + str(count)
            blf.position(font_id, px, py, 0)
            # blf.draw(font_id, text)
            draw_text(text)

            py += th
            draw_any = True

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glScissor(*glscissorbox)
        bgl.glLineWidth(1.0)
        # blf.disable(font_id, blf.SHADOW)

        if draw_any:
            cls.draw_regions_prev.add(region.as_pointer())
def draw_measurements_callback(self, context):
    sce = context.scene

    draw = 0
    if hasattr(sce, "measure_panel_draw"):
        draw = sce.measure_panel_draw

    # 2D drawing code example
    #bgl.glBegin(bgl.GL_LINE_STRIP)
    #bgl.glVertex2i(0, 0)
    #bgl.glVertex2i(80, 100)
    #bgl.glEnd()

    # Get measured 3D points and colors.
    line = getMeasurePoints(context)
    if (line and draw):
        p1, p2, color = line

        # Get and convert the Perspective Matrix of the current view/region.
        view3d = bpy.context
        region = view3d.region_data
        perspMatrix = region.perspective_matrix
        tempMat = [perspMatrix[i][j] for i in range(4) for j in range(4)]
        perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

        # ---
        # Store previous OpenGL settings.
        # Store MatrixMode
        MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
        MatrixMode_prev = MatrixMode_prev[0]

        # Store projection matrix
        ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)

        # Store Line width
        lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
        lineWidth_prev = lineWidth_prev[0]

        # Store GL_BLEND
        blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
        blend_prev = blend_prev[0]

        line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
        line_stipple_prev = line_stipple_prev[0]

        # Store glColor4f
        color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

        # ---
        # Prepare for 3D drawing
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadMatrixf(perspBuff)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_LINE_STIPPLE)

        # ---
        # Draw 3D stuff.
        width = 1
        bgl.glLineWidth(width)
        # X
        bgl.glColor4f(1, 0, 0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p2[0], p1[1], p1[2])
        bgl.glEnd()
        # Y
        bgl.glColor4f(0, 1, 0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p1[0], p2[1], p1[2])
        bgl.glEnd()
        # Z
        bgl.glColor4f(0, 0, 1, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p1[0], p1[1], p2[2])
        bgl.glEnd()

        # Dist
        width = 2
        bgl.glLineWidth(width)
        bgl.glColor4f(color[0], color[1], color[2], color[3])
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p2[0], p2[1], p2[2])
        bgl.glEnd()

        # ---
        # Restore previous OpenGL settings
        bgl.glLoadIdentity()
        bgl.glMatrixMode(MatrixMode_prev)
        bgl.glLoadMatrixf(ProjMatrix_prev)
        bgl.glLineWidth(lineWidth_prev)
        if not blend_prev:
            bgl.glDisable(bgl.GL_BLEND)
        if not line_stipple_prev:
            bgl.glDisable(bgl.GL_LINE_STIPPLE)
        bgl.glColor4f(color_prev[0],
            color_prev[1],
            color_prev[2],
            color_prev[3])

        # ---
        # Draw (2D) text
        # We do this after drawing the lines so
        # we can draw it OVER the line.
        coord_2d = location_3d_to_region_2d(context.region,
                                            context.space_data.region_3d,
                                            p1.lerp(p2, 0.5),
                                            )
        OFFSET_LINE = 10   # Offset the text a bit to the right.
        OFFSET_Y = 15      # Offset of the lines.
        OFFSET_VALUE = 30  # Offset of value(s) from the text.
        dist = (p1 - p2).length

        # Write distance value into the scene property,
        # so we can display it in the panel & refresh the panel.
        if hasattr(sce, "measure_panel_dist"):
            sce.measure_panel_dist = dist
            context.area.tag_redraw()

        texts = [("Dist:", round(dist, PRECISION)),
            ("X:", round(abs(p1[0] - p2[0]), PRECISION)),
            ("Y:", round(abs(p1[1] - p2[1]), PRECISION)),
            ("Z:", round(abs(p1[2] - p2[2]), PRECISION))]

        # Draw all texts
        # @todo Get user pref for text color in 3D View
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        blf.size(0, 12, 72)  # Prevent font size to randomly change.

        loc_x = coord_2d[0] + OFFSET_LINE
        loc_y = coord_2d[1]
        for t in texts:
            text = t[0]
            value = str(t[1]) + " BU"

            blf.position(0, loc_x, loc_y, 0)
            blf.draw(0, text)
            blf.position(0, loc_x + OFFSET_VALUE, loc_y, 0)
            blf.draw(0, value)

            loc_y -= OFFSET_Y

    # Handle mesh surface area calulations
    if (sce.measure_panel_calc_area):
        # Get a single selected object (or nothing).
        obj = getSingleObject(context)

        if (context.mode == 'EDIT_MESH'):
            obj = context.active_object

            if (obj and obj.type == 'MESH' and obj.data):
                # "Note: a Mesh will return the selection state of the mesh
                # when EditMode was last exited. A Python script operating
                # in EditMode must exit EditMode before getting the current
                # selection state of the mesh."
                # http://www.blender.org/documentation/249PythonDoc/
                # /Mesh.MVert-class.html#sel
                # We can only provide this by existing & re-entering EditMode.
                # @todo: Better way to do this?

                # Get mesh data from Object.
                mesh = obj.data

                # Get transformation matrix from object.
                ob_mat = obj.matrix_world
                # Also make an inversed copy! of the matrix.
                ob_mat_inv = ob_mat.copy()
                Matrix.invert(ob_mat_inv)

                # Get the selected vertices.
                # @todo: Better (more efficient) way to do this?
                verts_selected = [v for v in mesh.vertices if v.select == 1]

                if len(verts_selected) >= 3:
                    # Get selected faces
                    # @todo: Better (more efficient) way to do this?
                    faces_selected = [f for f in mesh.faces
                        if f.select == 1]

                    if len(faces_selected) > 0:
                        area, normal = objectSurfaceArea(obj, True,
                            measureGlobal(sce))
                        if (area >= 0):
                            sce.measure_panel_area1 = area
                            sce.measure_panel_normal1 = normal

        elif (context.mode == 'OBJECT'):
            # We are working in object mode.

            if len(context.selected_objects) > 2:
                return
# @todo Make this work again.
#                # We have more that 2 objects selected...
#
#                mesh_objects = [o for o in context.selected_objects
#                    if (o.type == 'MESH')]

#                if (len(mesh_objects) > 0):
#                    # ... and at least one of them is a mesh.
#
#                    for o in mesh_objects:
#                        area = objectSurfaceArea(o, False,
#                            measureGlobal(sce))
#                        if (area >= 0):
#                            #row.label(text=o.name, icon='OBJECT_DATA')
#                            #row.label(text=str(round(area, PRECISION))
#                            #    + " BU^2")

            elif len(context.selected_objects) == 2:
                # 2 objects selected.

                obj1, obj2 = context.selected_objects

                # Calculate surface area of the objects.
                area1, normal1 = objectSurfaceArea(obj1, False,
                    measureGlobal(sce))
                area2, normal2 = objectSurfaceArea(obj2, False,
                    measureGlobal(sce))
                sce.measure_panel_area1 = area1
                sce.measure_panel_area2 = area2
                sce.measure_panel_normal1 = normal1
                sce.measure_panel_normal2 = normal2

            elif (obj):
                # One object selected.

                # Calculate surface area of the object.
                area, normal = objectSurfaceArea(obj, False,
                    measureGlobal(sce))

                if (area >= 0):
                    sce.measure_panel_area1 = area
                    sce.measure_panel_normal1 = normal

    if (sce.measure_panel_calc_volume):
        obj = getSingleObject(context)

        if (context.mode == 'OBJECT'):
            # We are working in object mode.

            #if len(context.selected_objects) > 2:       # TODO

            #el
            if len(context.selected_objects) == 2:
                # 2 objects selected.

                obj1, obj2 = context.selected_objects

                # Calculate surface area of the objects.
                volume1 = objectVolume(obj1, measureGlobal(sce))
                volume2 = objectVolume(obj2, measureGlobal(sce))

                sce.measure_panel_volume1 = volume1
                sce.measure_panel_volume2 = volume2

            elif (obj):
                # One object selected.

                # Calculate surface area of the object.
                volume1 = objectVolume(obj, measureGlobal(sce))

                sce.measure_panel_volume1 = volume1
Example #48
0
    def draw(self, area, region_data):
        """
        Draw avatar view in given context
        """
        # TODO: Add this color to addon option
        color = (1.0, 1.0, 0.5, 1.0)
        alpha = 2.0*math.atan((18.0/2.0)/self.lens.value[0])
        dist = 0.5/(math.tan(alpha/2.0))
        height = 1.0
        if self.height.value[0] == 0:
            width = 0.7
        else:
            width = self.width.value[0]/self.height.value[0]
                    
        points = {}
        points['border'] = [None, None, None, None]
        points['center'] = [None]
        
        # Points of face
        points['right_eye'] = [mathutils.Vector((0.25, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((0.3, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((0.3, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((0.25, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((0.25, 0.25, self.distance.value[0] - dist))]
        points['left_eye'] = [mathutils.Vector((-0.25, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.3, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.3, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.25, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.25, 0.25, self.distance.value[0] - dist))]
        
        points['mouth'] = [mathutils.Vector((-0.40912365913391113, -0.11777058243751526, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.3441678285598755, -0.15873458981513977, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.2563667893409729, -0.1998385488986969, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.18191590905189514, -0.22385218739509583, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.10375960171222687, -0.23957833647727966, self.distance.value[0] - dist)), \
            mathutils.Vector((0.0, -0.2464955747127533, self.distance.value[0] - dist)), \
            mathutils.Vector((0.10375960171222687, -0.23957833647727966, self.distance.value[0] - dist)), \
            mathutils.Vector((0.18191590905189514, -0.22385218739509583, self.distance.value[0] - dist)), \
            mathutils.Vector((0.2563667893409729, -0.1998385488986969, self.distance.value[0] - dist)), \
            mathutils.Vector((0.3441678285598755, -0.15873458981513977, self.distance.value[0] - dist)), \
            mathutils.Vector((0.40912365913391113, -0.11777058243751526, self.distance.value[0] - dist))]            
                
        # Put border points of camera to basic position
        points['border'][0] = mathutils.Vector((-width/2.0, \
            -0.5, \
            self.distance.value[0] - dist,
            1.0))
        points['border'][1] = mathutils.Vector((width/2.0, \
            -0.5, \
            self.distance.value[0] - dist,
            1.0))
        points['border'][2] = mathutils.Vector((width/2.0, \
            0.5, \
            self.distance.value[0] - dist, \
            1.0))
        points['border'][3] = mathutils.Vector((-width/2.0, \
            0.5, \
            self.distance.value[0] - dist, \
            1.0))
        
        # Center of view
        points['center'][0] = mathutils.Vector((0.0, \
            0.0, \
            self.distance.value[0], \
            1.0))        
        
        # Create transformation (rotation) matrix
        rot_matrix = mathutils.Quaternion(self.rotation.value).to_matrix().to_4x4()
        
        # Transform points in all point groups
        for point_group in points.values():
            for index in range(len(point_group)):
                # Rotate points
                point_group[index] = (rot_matrix*point_group[index]).to_3d()
                # Move points
                point_group[index] += mathutils.Vector(self.location.value)
        
        # Get & convert the Perspective Matrix of the current view/region.
        perspMatrix = region_data.perspective_matrix
        tempMat = [perspMatrix[j][i] for i in range(4) for j in range(4)]
        perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)
    
        # Store previous OpenGL settings.
        # Store MatrixMode
        MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
        MatrixMode_prev = MatrixMode_prev[0]
    
        # Store projection matrix
        ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)
    
        # Store Line width
        lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
        lineWidth_prev = lineWidth_prev[0]
    
        # Store GL_BLEND
        blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
        blend_prev = blend_prev[0]
        
        # Store GL_DEPTH_TEST
        depth_test_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_DEPTH_TEST, depth_test_prev)
        depth_test_prev = depth_test_prev[0]
            
        # Store GL_LINE_STIPPLE
        line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
        line_stipple_prev = line_stipple_prev[0]
    
        # Store glColor4f
        col_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, col_prev)
        
        # Prepare for 3D drawing
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadMatrixf(perspBuff)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_DEPTH_TEST)
                
        # Draw "Look At" point
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor4f(color[0], color[1], color[2], color[3])
        
        bgl.glVertex3f(self.location.value[0]+0.1, \
            self.location.value[1], \
            self.location.value[2])
        bgl.glVertex3f(self.location.value[0]-0.1, \
            self.location.value[1], \
            self.location.value[2])
        
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1]+0.1, \
            self.location.value[2])
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1]-0.1, \
            self.location.value[2])
        
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1], \
            self.location.value[2]+0.1)
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1], \
            self.location.value[2]-0.1)
        
        bgl.glEnd()
        
        border = points['border']
        center = points['center']
        
        # Draw border of camera
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glVertex3f(border[1][0], border[1][1], border[1][2])
        bgl.glVertex3f(border[2][0], border[2][1], border[2][2])
        bgl.glVertex3f(border[3][0], border[3][1], border[3][2])
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glEnd()
        
        # Draw left eye
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['left_eye']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()

        # Draw right eye
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['right_eye']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()
        
        # Draw mouth
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['mouth']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()
        
        # Draw dashed lines from center of "camera" to border of camera        
        bgl.glEnable(bgl.GL_LINE_STIPPLE)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[1][0], border[1][1], border[1][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[2][0], border[2][1], border[2][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[3][0], border[3][1], border[3][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glEnd()
        
        # Draw dashed line from Look At point and center of camera
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1], \
            self.location.value[2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glEnd()
        bgl.glDisable(bgl.GL_LINE_STIPPLE)    

        # Restore previous OpenGL settings
        bgl.glLoadIdentity()
        bgl.glMatrixMode(MatrixMode_prev)
        bgl.glLoadMatrixf(ProjMatrix_prev)
        bgl.glLineWidth(lineWidth_prev)
        if not blend_prev:
            bgl.glDisable(bgl.GL_BLEND)
        if not line_stipple_prev:
            bgl.glDisable(bgl.GL_LINE_STIPPLE)
        if not depth_test_prev:
            bgl.glDisable(bgl.GL_DEPTH_TEST)

        # Draw username
        coord_2d = location_3d_to_region_2d(
            area.regions[4],
            region_data,
            center[0])
        font_id, font_size, my_dpi = 0, 12, 72 # TODO: add to addon options
        blf.size(font_id, font_size, my_dpi)
        text_width, text_height = blf.dimensions(font_id, self.username)
        blf.position(font_id, coord_2d[0], coord_2d[1], 0)
        blf.draw(font_id, self.username)

        bgl.glColor4f(col_prev[0], col_prev[1], col_prev[2], col_prev[3])
def get_viewport():
    view = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view)
    return view
Example #50
0
 def _get_integer(self, arg):
     buf = bgl.Buffer(bgl.GL_INT, 1)
     bgl.glGetIntegerv(arg, buf)
     return int(buf[0])
Example #51
0
def render_opengl(self, context):
    from math import ceil

    layers = []
    scene = context.scene
    for x in range(0, 20):
        if scene.layers[x] is True:
            layers.extend([x])

    objlist = context.scene.objects
    render_scale = scene.render.resolution_percentage / 100

    width = int(scene.render.resolution_x * render_scale)
    height = int(scene.render.resolution_y * render_scale)
    
    # I cant use file_format becuase the pdf writer needs jpg format
    # the file_format returns 'JPEG' not 'JPG'
#     file_format = context.scene.render.image_settings.file_format.lower()
    ren_path = bpy.path.abspath(bpy.context.scene.render.filepath) + ".jpg"
    
#     if len(ren_path) > 0:
#         if ren_path.endswith(os.path.sep):
#             initpath = os.path.realpath(ren_path) + os.path.sep
#         else:
#             (initpath, filename) = os.path.split(ren_path)
#         outpath = os.path.join(initpath, "ogl_tmp.png")
#     else:
#         self.report({'ERROR'}, "Invalid render path")
#         return False

    img = get_render_image(ren_path)
    
    if img is None:
        self.report({'ERROR'}, "Invalid render path:" + ren_path)
        return False

    tile_x = 240
    tile_y = 216
    row_num = ceil(height / tile_y)
    col_num = ceil(width / tile_x)
    
    cut4 = (col_num * tile_x * 4) - width * 4  
    totpixel4 = width * height * 4 

    viewport_info = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)
    
    img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)

    # 2.77 API change
    if bpy.app.version >= (2, 77, 0):
        tex = img.bindcode[0]
    else:
        tex = img.bindcode
    
    if context.scene.name in bpy.data.images:
        old_img = bpy.data.images[context.scene.name]
        old_img.user_clear()
        bpy.data.images.remove(old_img)
             
    img_result = bpy.data.images.new(context.scene.name, width, height)        
    
    tmp_pixels = [1] * totpixel4

    #---------- Loop for all tiles
    for row in range(0, row_num):
        for col in range(0, col_num):
            buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
            bgl.glDisable(bgl.GL_SCISSOR_TEST)  # if remove this line, get blender screenshot not image
            bgl.glViewport(0, 0, tile_x, tile_y)

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

            # defines ortographic view for single tile
            x1 = tile_x * col
            y1 = tile_y * row
            bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y)

            # Clear
            bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
            bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

            bgl.glEnable(bgl.GL_TEXTURE_2D)
            bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

            # defines drawing area
            bgl.glBegin(bgl.GL_QUADS)

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

            bgl.glTexCoord2f(1.0, 0.0)
            bgl.glVertex2f(width, 0.0)

            bgl.glTexCoord2f(1.0, 1.0)
            bgl.glVertex2f(width, height)

            bgl.glTexCoord2f(0.0, 1.0)
            bgl.glVertex2f(0.0, height)

            bgl.glEnd()

            for obj in objlist:
                if obj.mv.type == 'VISDIM_A':
                    for x in range(0, 20):
                        if obj.layers[x] is True:
                            if x in layers:
                                opengl_dim = obj.mv.opengl_dim
                                if not opengl_dim.hide:
                                    draw_dimensions(context, obj, opengl_dim, None, None)
                            break 

            #---------- copy pixels to temporary area
            bgl.glFinish()
            bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)  # read image data
            for y in range(0, tile_y):
                # final image pixels position
                p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4)
                p2 = p1 + (tile_x * 4)
                # buffer pixels position
                b1 = y * width * 4
                b2 = b1 + (tile_x * 4)

                if p1 < totpixel4:  # avoid pixel row out of area
                    if col == col_num - 1:  # avoid pixel columns out of area
                        p2 -= cut4
                        b2 -= cut4

                    tmp_pixels[p1:p2] = buffer[b1:b2]

    img_result.pixels = tmp_pixels[:]
    img.gl_free()

    img.user_clear()
    bpy.data.images.remove(img)
    os.remove(ren_path)
    bgl.glEnable(bgl.GL_SCISSOR_TEST)

    #---------- restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    
    if img_result is not None:            
        return img_result
Example #52
0
def status_image():
    """
    Show the corrensponding Image for the status
    """
    imageHeight = windowHeight * 0.075
    imageWidth = imageHeight

    x = windowWidth * 0.35 - imageWidth/2
    y = windowHeight * 0.45 - imageHeight/2
    
    gl_position = [[x, y],[x+imageWidth, y],[x+imageWidth, y+imageHeight],[x, y+imageHeight]]

    cam = logic.getCurrentScene().active_camera

    # get the suffix of the human to reference the right objects
    suffix = cam.name[-4:] if cam.name[-4] == "." else ""

    hand = objects['Hand_Grab.R' + suffix]

    # select the right Image
    if hand["selected"]:
        tex_id = closed_id
    else:
        tex_id = open_id

    
    view_buf = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
    view = view_buf.to_list() if hasattr(view_buf, "to_list") else view_buf.list
    # Save the state
    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)      
    # Disable depth test so we always draw over things
    bgl.glDisable(bgl.GL_DEPTH_TEST)   
    # Disable lighting so everything is shadless
    bgl.glDisable(bgl.GL_LIGHTING)   
    # Unbinding the texture prevents BGUI frames from somehow picking up on
    # color of the last used texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)      
    # Make sure we're using smooth shading instead of flat
    bgl.glShadeModel(bgl.GL_SMOOTH)
    # Setup the matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, view[2], 0, view[3])
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    
    
    bgl.glEnable(bgl.GL_TEXTURE_2D)
    # Enable alpha blending
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    # Bind the texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex_id)
    # Draw the textured quad
    bgl.glColor4f(1, 1, 1, 1)
    bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
    bgl.glPolygonOffset(1.0, 1.0)
    bgl.glBegin(bgl.GL_QUADS)
    for i in range(4):
       bgl.glTexCoord2f(texco[i][0], texco[i][1])
       bgl.glVertex2f(gl_position[i][0], gl_position[i][1])
    bgl.glEnd()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
    bgl.glPopAttrib()
Example #53
0
def write_sysinfo(filepath):
    import sys

    import subprocess

    import bpy
    import bgl

    # pretty repr
    def prepr(v):
        r = repr(v)
        vt = type(v)
        if vt is bytes:
            r = r[2:-1]
        elif vt is list or vt is tuple:
            r = r[1:-1]
        return r

    with open(filepath, 'w', encoding="utf-8") as output:
        try:
            header = "= Blender %s System Information =\n" % bpy.app.version_string
            lilies = "%s\n\n" % ((len(header) - 1) * "=")
            output.write(lilies[:-1])
            output.write(header)
            output.write(lilies)

            def title(text):
                return "\n%s:\n%s" % (text, lilies)

            # build info
            output.write(title("Blender"))
            output.write(
                "version: %s, branch: %s, commit date: %s %s, hash: %s, type: %s\n" %
                (bpy.app.version_string,
                 prepr(bpy.app.build_branch),
                 prepr(bpy.app.build_commit_date),
                 prepr(bpy.app.build_commit_time),
                 prepr(bpy.app.build_hash),
                 prepr(bpy.app.build_type),
                 ))

            output.write("build date: %s, %s\n" % (prepr(bpy.app.build_date), prepr(bpy.app.build_time)))
            output.write("platform: %s\n" % prepr(bpy.app.build_platform))
            output.write("binary path: %s\n" % prepr(bpy.app.binary_path))
            output.write("build cflags: %s\n" % prepr(bpy.app.build_cflags))
            output.write("build cxxflags: %s\n" % prepr(bpy.app.build_cxxflags))
            output.write("build linkflags: %s\n" % prepr(bpy.app.build_linkflags))
            output.write("build system: %s\n" % prepr(bpy.app.build_system))

            # python info
            output.write(title("Python"))
            output.write("version: %s\n" % (sys.version))
            output.write("paths:\n")
            for p in sys.path:
                output.write("\t%r\n" % p)

            output.write(title("Python (External Binary)"))
            output.write("binary path: %s\n" % prepr(bpy.app.binary_path_python))
            try:
                py_ver = prepr(subprocess.check_output([
                    bpy.app.binary_path_python,
                    "--version",
                ]).strip())
            except Exception as e:
                py_ver = str(e)
            output.write("version: %s\n" % py_ver)
            del py_ver

            output.write(title("Directories"))
            output.write("scripts:\n")
            for p in bpy.utils.script_paths():
                output.write("\t%r\n" % p)
            output.write("user scripts: %r\n" % (bpy.utils.script_path_user()))
            output.write("pref scripts: %r\n" % (bpy.utils.script_path_pref()))
            output.write("datafiles: %r\n" % (bpy.utils.user_resource('DATAFILES')))
            output.write("config: %r\n" % (bpy.utils.user_resource('CONFIG')))
            output.write("scripts : %r\n" % (bpy.utils.user_resource('SCRIPTS')))
            output.write("autosave: %r\n" % (bpy.utils.user_resource('AUTOSAVE')))
            output.write("tempdir: %r\n" % (bpy.app.tempdir))

            output.write(title("FFmpeg"))
            ffmpeg = bpy.app.ffmpeg
            if ffmpeg.supported:
                for lib in ("avcodec", "avdevice", "avformat", "avutil", "swscale"):
                    output.write(
                        "%s:%s%r\n" % (lib, " " * (10 - len(lib)),
                                       getattr(ffmpeg, lib + "_version_string")))
            else:
                output.write("Blender was built without FFmpeg support\n")

            if bpy.app.build_options.sdl:
                output.write(title("SDL"))
                output.write("Version: %s\n" % bpy.app.sdl.version_string)
                output.write("Loading method: ")
                if bpy.app.build_options.sdl_dynload:
                    output.write("dynamically loaded by Blender (WITH_SDL_DYNLOAD=ON)\n")
                else:
                    output.write("linked (WITH_SDL_DYNLOAD=OFF)\n")
                if not bpy.app.sdl.available:
                    output.write("WARNING: Blender could not load SDL library\n")

            output.write(title("Other Libraries"))
            ocio = bpy.app.ocio
            output.write("OpenColorIO: ")
            if ocio.supported:
                if ocio.version_string == "fallback":
                    output.write("Blender was built with OpenColorIO, " +
                                 "but it currently uses fallback color management.\n")
                else:
                    output.write("%s\n" % (ocio.version_string))
            else:
                output.write("Blender was built without OpenColorIO support\n")

            oiio = bpy.app.oiio
            output.write("OpenImageIO: ")
            if ocio.supported:
                output.write("%s\n" % (oiio.version_string))
            else:
                output.write("Blender was built without OpenImageIO support\n")

            output.write("OpenShadingLanguage: ")
            if bpy.app.build_options.cycles:
                if bpy.app.build_options.cycles_osl:
                    from _cycles import osl_version_string
                    output.write("%s\n" % (osl_version_string))
                else:
                    output.write("Blender was built without OpenShadingLanguage support in Cycles\n")
            else:
                output.write("Blender was built without Cycles support\n")

            opensubdiv = bpy.app.opensubdiv
            output.write("OpenSubdiv: ")
            if opensubdiv.supported:
                output.write("%s\n" % opensubdiv.version_string)
            else:
                output.write("Blender was built without OpenSubdiv support\n")

            openvdb = bpy.app.openvdb
            output.write("OpenVDB: ")
            if openvdb.supported:
                output.write("%s\n" % openvdb.version_string)
            else:
                output.write("Blender was built without OpenVDB support\n")

            alembic = bpy.app.alembic
            output.write("Alembic: ")
            if alembic.supported:
                output.write("%s\n" % alembic.version_string)
            else:
                output.write("Blender was built without Alembic support\n")

            if not bpy.app.build_options.sdl:
                output.write("SDL: Blender was built without SDL support\n")

            if bpy.app.background:
                output.write("\nOpenGL: missing, background mode\n")
            else:
                output.write(title("OpenGL"))
                version = bgl.glGetString(bgl.GL_RENDERER)
                output.write("renderer:\t%r\n" % version)
                output.write("vendor:\t\t%r\n" % (bgl.glGetString(bgl.GL_VENDOR)))
                output.write("version:\t%r\n" % (bgl.glGetString(bgl.GL_VERSION)))
                output.write("extensions:\n")

                limit = bgl.Buffer(bgl.GL_INT, 1)
                bgl.glGetIntegerv(bgl.GL_NUM_EXTENSIONS, limit)

                glext = []
                for i in range(limit[0]):
                    glext.append(bgl.glGetStringi(bgl.GL_EXTENSIONS, i))

                glext = sorted(glext)

                for l in glext:
                    output.write("\t%s\n" % l)

                output.write(title("Implementation Dependent OpenGL Limits"))
                bgl.glGetIntegerv(bgl.GL_MAX_ELEMENTS_VERTICES, limit)
                output.write("Maximum DrawElements Vertices:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_ELEMENTS_INDICES, limit)
                output.write("Maximum DrawElements Indices:\t%d\n" % limit[0])

                output.write("\nGLSL:\n")
                bgl.glGetIntegerv(bgl.GL_MAX_VARYING_FLOATS, limit)
                output.write("Maximum Varying Floats:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_VERTEX_ATTRIBS, limit)
                output.write("Maximum Vertex Attributes:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_VERTEX_UNIFORM_COMPONENTS, limit)
                output.write("Maximum Vertex Uniform Components:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, limit)
                output.write("Maximum Fragment Uniform Components:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, limit)
                output.write("Maximum Vertex Image Units:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_TEXTURE_IMAGE_UNITS, limit)
                output.write("Maximum Fragment Image Units:\t%d\n" % limit[0])
                bgl.glGetIntegerv(bgl.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, limit)
                output.write("Maximum Pipeline Image Units:\t%d\n" % limit[0])

            if bpy.app.build_options.cycles:
                import cycles
                output.write(title("Cycles"))
                output.write(cycles.engine.system_info())

            import addon_utils
            addon_utils.modules()
            output.write(title("Enabled add-ons"))
            for addon in bpy.context.preferences.addons.keys():
                addon_mod = addon_utils.addons_fake_modules.get(addon, None)
                if addon_mod is None:
                    output.write("%s (MISSING)\n" % (addon))
                else:
                    output.write("%s (version: %s, path: %s)\n" %
                                 (addon, addon_mod.bl_info.get('version', "UNKNOWN"), addon_mod.__file__))
        except Exception as e:
            output.write("ERROR: %s\n" % e)
Example #54
0
def generate_icon(name, verts=None, faces=None):
    pcoll = preview_collections["shape_types"]
    if name in pcoll:
        thumb = pcoll.get(name)
    else:
        thumb = pcoll.new(name)
    thumb.image_size = (200, 200)

    if verts is not None:
        import bgl

        polygon_color = bpy.context.user_preferences.themes[0].view_3d.edge_facesel
        edge_color = bpy.context.user_preferences.themes[0].view_3d.edge_select
        vertex_color = bpy.context.user_preferences.themes[0].view_3d.vertex_select
        clear_color = bpy.context.user_preferences.themes[0].user_interface.wcol_menu.inner

        viewport_info = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)
        buffer = bgl.Buffer(bgl.GL_FLOAT, 200 * 200 * 4)

        bgl.glDisable(bgl.GL_SCISSOR_TEST)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glViewport(0, 0, 200, 200)

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

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

        bgl.glLineWidth(4.0)
        bgl.glPointSize(10.0)

        bgl.glClearColor(*clear_color)
        bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

        if faces is None:
            bgl.glBegin(bgl.GL_POLYGON)
            bgl.glColor3f(*polygon_color)
            for vert in verts:
                bgl.glVertex2f(*vert)
            bgl.glEnd()
        else:
            bgl.glBegin(bgl.GL_TRIANGLES)
            bgl.glColor3f(*polygon_color)
            for face in faces:
                bgl.glVertex2f(*verts[face[0]])
                bgl.glVertex2f(*verts[face[1]])
                bgl.glVertex2f(*verts[face[2]])
            bgl.glEnd()

        bgl.glBegin(bgl.GL_LINE_LOOP)
        bgl.glColor3f(*edge_color)
        for vert in verts:
            bgl.glVertex2f(*vert)
        bgl.glEnd()

        bgl.glBegin(bgl.GL_POINTS)
        bgl.glColor3f(*vertex_color)
        for vert in verts:
            bgl.glVertex2f(*vert)
        bgl.glEnd()

        bgl.glReadPixels(0, 0, 200, 200, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)
        bgl.glEnable(bgl.GL_SCISSOR_TEST)
        bgl.glLineWidth(1.0)
        bgl.glPointSize(1.0)

        buffer = buffer[:]
        for idx in range(0, 200 * 200 * 4, 4):
            if (
                buffer[idx] == clear_color[0]
                and buffer[idx + 1] == clear_color[1]
                and buffer[idx + 2] == clear_color[2]
            ):
                buffer[idx + 3] = 0.0

        thumb.image_pixels_float = buffer
Example #55
0
def glGetIntegerv(pname, params):
    bgl.glGetIntegerv(pname, params)
Example #56
0
def _store_current_shader_state(cls):
    bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM, cls.cur_program)
    bgl.glGetIntegerv(bgl.GL_VERTEX_ARRAY_BINDING, cls.cur_vao)
    bgl.glGetIntegerv(bgl.GL_ARRAY_BUFFER_BINDING, cls.cur_vbo)
    bgl.glGetIntegerv(bgl.GL_ELEMENT_ARRAY_BUFFER_BINDING, cls.cur_ebo)
Example #57
0
    def draw_callback_px(self, context):
        use_texture = self.use_texture
        if not use_texture:
            if context.region != self.region:
                return

        U = context.user_preferences
        prefs = MouseGesturePreferences.get_instance()
        dpi = U.system.dpi
        widget_unit = int((PIXEL_SIZE * dpi * 20 + 36) / 72)

        font_id = 0
        theme_style = U.ui_styles[0]
        blf.size(font_id, theme_style.widget.points, dpi)
        bgl.glEnable(bgl.GL_BLEND)

        bgl.glColor3f(*U.themes['Default'].view_3d.space.text_hi)

        win = context.window
        w, h = win.width, win.height

        if use_texture:
            bgl.glDisable(bgl.GL_SCISSOR_TEST)

        with window_space(win):
            if use_texture:
                draw_texture(0, 0, w, h, self.texture_back)

            # draw origin
            coords = self.coords + [self.mco]
            bgl.glLineWidth(2)
            r1 = prefs.threshold
            r2 = r1 + 5
            x, y = coords[0]
            bgl.glBegin(bgl.GL_LINES)
            for i in range(4):
                a = math.pi / 2 * i + math.pi / 4
                bgl.glVertex2f(x + r1 * math.cos(a),
                               y + r1 * math.sin(a))
                bgl.glVertex2f(x + r2 * math.cos(a),
                               y + r2 * math.sin(a))
            bgl.glEnd()
            bgl.glLineWidth(1)

            # draw lines
            bgl.glEnable(bgl.GL_LINE_STIPPLE)
            bgl.glLineStipple(1, int(0b101010101010101))  # (factor, pattern)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for v in coords:
                bgl.glVertex2f(v[0], v[1])
            bgl.glEnd()
            bgl.glLineStipple(1, 1)
            bgl.glDisable(bgl.GL_LINE_STIPPLE)

        if use_texture:
            bgl.glEnable(bgl.GL_SCISSOR_TEST)

        # draw txt

        xmin, ymin, xmax, ymax = self.region_drawing_rectangle(
            context, self.area, self.region)
        xmin += self.region.x
        ymin += self.region.y
        xmax += self.region.x
        ymax += self.region.y

        if self.area.type == 'VIEW_3D':
            if U.view.show_mini_axis:
                # view3d_draw.c: 1019: draw_selected_name()
                posx = xmin + widget_unit + U.view.mini_axis_size * 2
            else:
                # view3d_draw.c: 928: draw_selected_name()
                posx = xmin + 1.5 * widget_unit
            posy = ymin + widget_unit * 1.5
        else:
            posx = xmin + widget_unit * 0.5
            posy = ymin + widget_unit * 0.5
        char_space = 5

        group = prefs.gesture_groups.get(self.group)
        use_relative = group and group.use_relative
        gesture = self.gesture_rel if use_relative else self.gesture_abs
        # 文字はregionに収まるように(はみ出すと見た目が悪いから)
        scissor_box = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
        bgl.glScissor(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)
        with window_space(win):
            if gesture:
                x = posx
                for txt in gesture:
                    blf.position(font_id, x, posy, 0)
                    blf.draw(font_id, txt)
                    text_width, text_height = blf.dimensions(font_id, txt)
                    x += text_width + char_space
            if self.item:
                blf.position(font_id, posx, posy + widget_unit, 0)
                blf.draw(font_id, self.item.name)
        bgl.glScissor(*scissor_box)

        # restore opengl defaults
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Example #58
0
def write_sysinfo(op):
    import textwrap

    output_filename = "system-info.txt"

    output = bpy.data.texts.get(output_filename)
    if output:
        output.clear()
    else:
        output = bpy.data.texts.new(name=output_filename)

    # pretty repr
    def prepr(v):
        r = repr(v)
        vt = type(v)
        if vt is bytes:
            r = r[2:-1]
        elif vt is list or vt is tuple:
            r = r[1:-1]
        return r


    header = "= Blender %s System Information =\n" % bpy.app.version_string
    lilies = "%s\n\n" % ((len(header) - 1) * "=")
    output.write(lilies[:-1])
    output.write(header)
    output.write(lilies)

    def title(text):
        return "\n%s:\n%s" % (text, lilies)

    # build info
    output.write(title("Blender"))
    output.write("version: %s, branch: %s, commit date: %s %s, hash: %s, type: %s\n" %
        (bpy.app.version_string,
         prepr(bpy.app.build_branch),
         prepr(bpy.app.build_commit_date),
         prepr(bpy.app.build_commit_time),
         prepr(bpy.app.build_hash),
         prepr(bpy.app.build_type),
         ))

    output.write("build date: %s, %s\n" % (prepr(bpy.app.build_date), prepr(bpy.app.build_time)))
    output.write("platform: %s\n" % prepr(bpy.app.build_platform))
    output.write("binary path: %s\n" % prepr(bpy.app.binary_path))
    output.write("build cflags: %s\n" % prepr(bpy.app.build_cflags))
    output.write("build cxxflags: %s\n" % prepr(bpy.app.build_cxxflags))
    output.write("build linkflags: %s\n" % prepr(bpy.app.build_linkflags))
    output.write("build system: %s\n" % prepr(bpy.app.build_system))

    # python info
    output.write(title("Python"))
    output.write("version: %s\n" % (sys.version))
    output.write("paths:\n")
    for p in sys.path:
        output.write("\t%r\n" % p)

    output.write(title("Directories"))
    output.write("scripts:\n")
    for p in bpy.utils.script_paths():
        output.write("\t%r\n" % p)
    output.write("user scripts: %r\n" % (bpy.utils.script_path_user()))
    output.write("pref scripts: %r\n" % (bpy.utils.script_path_pref()))
    output.write("datafiles: %r\n" % (bpy.utils.user_resource('DATAFILES')))
    output.write("config: %r\n" % (bpy.utils.user_resource('CONFIG')))
    output.write("scripts : %r\n" % (bpy.utils.user_resource('SCRIPTS')))
    output.write("autosave: %r\n" % (bpy.utils.user_resource('AUTOSAVE')))
    output.write("tempdir: %r\n" % (bpy.app.tempdir))

    output.write(title("FFmpeg"))
    ffmpeg = bpy.app.ffmpeg
    if ffmpeg.supported:
        for lib in ("avcodec", "avdevice", "avformat", "avutil", "swscale"):
            output.write("%s:%s%r\n" % (lib, " " * (10 - len(lib)),
                         getattr(ffmpeg, lib + "_version_string")))
    else:
        output.write("Blender was built without FFmpeg support\n")

    if bpy.app.build_options.sdl:
        output.write(title("SDL"))
        output.write("Version: %s\n" % bpy.app.sdl.version_string)
        output.write("Loading method: ")
        if bpy.app.build_options.sdl_dynload:
            output.write("dynamically loaded by Blender (WITH_SDL_DYNLOAD=ON)\n")
        else:
            output.write("linked (WITH_SDL_DYNLOAD=OFF)\n")
        if not bpy.app.sdl.available:
            output.write("WARNING: Blender could not load SDL library\n")

    output.write(title("Other Libraries"))
    ocio = bpy.app.ocio
    output.write("OpenColorIO: ")
    if ocio.supported:
        if ocio.version_string == "fallback":
            output.write("Blender was built with OpenColorIO, " +
                         "but it currently uses fallback color management.\n")
        else:
            output.write("%s\n" % (ocio.version_string))
    else:
        output.write("Blender was built without OpenColorIO support\n")

    oiio = bpy.app.oiio
    output.write("OpenImageIO: ")
    if ocio.supported:
        output.write("%s\n" % (oiio.version_string))
    else:
        output.write("Blender was built without OpenImageIO support\n")

    output.write("OpenShadingLanguage: ")
    if bpy.app.build_options.cycles:
        if bpy.app.build_options.cycles_osl:
            from _cycles import osl_version_string
            output.write("%s\n" % (osl_version_string))
        else:
            output.write("Blender was built without OpenShadingLanguage support in Cycles\n")
    else:
        output.write("Blender was built without Cycles support\n")

    if not bpy.app.build_options.sdl:
        output.write("SDL: Blender was built without SDL support\n")

    if bpy.app.background:
        output.write("\nOpenGL: missing, background mode\n")
    else:
        output.write(title("OpenGL"))
        version = bgl.glGetString(bgl.GL_RENDERER)
        output.write("renderer:\t%r\n" % version)
        output.write("vendor:\t\t%r\n" % (bgl.glGetString(bgl.GL_VENDOR)))
        output.write("version:\t%r\n" % (bgl.glGetString(bgl.GL_VERSION)))
        output.write("extensions:\n")

        glext = bgl.glGetString(bgl.GL_EXTENSIONS)
        glext = textwrap.wrap(glext, 70)
        for l in glext:
            output.write("\t%s\n" % l)

        output.write(title("Implementation Dependent OpenGL Limits"))
        limit = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_MAX_TEXTURE_UNITS, limit)
        output.write("Maximum Fixed Function Texture Units:\t%d\n" % limit[0])

        output.write("\nGLSL:\n")
        if version[0] > '1':
            bgl.glGetIntegerv(bgl.GL_MAX_VARYING_FLOATS, limit)
            output.write("Maximum Varying Floats:\t%d\n" % limit[0])
            bgl.glGetIntegerv(bgl.GL_MAX_VERTEX_ATTRIBS, limit)
            output.write("Maximum Vertex Attributes:\t%d\n" % limit[0])
            bgl.glGetIntegerv(bgl.GL_MAX_VERTEX_UNIFORM_COMPONENTS, limit)
            output.write("Maximum Vertex Uniform Components:\t%d\n" % limit[0])
            bgl.glGetIntegerv(bgl.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, limit)
            output.write("Maximum Fragment Uniform Components:\t%d\n" % limit[0])
            bgl.glGetIntegerv(bgl.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, limit)
            output.write("Maximum Vertex Image Units:\t%d\n" % limit[0])
            bgl.glGetIntegerv(bgl.GL_MAX_TEXTURE_IMAGE_UNITS, limit)
            output.write("Maximum Fragment Image Units:\t%d\n" % limit[0])
            bgl.glGetIntegerv(bgl.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, limit)
            output.write("Maximum Pipeline Image Units:\t%d\n" % limit[0])

    if bpy.app.build_options.cycles:
        import cycles
        output.write(title("Cycles"))
        output.write(cycles.engine.system_info())

    output.current_line_index = 0

    op.report({'INFO'}, "System information generated in 'system-info.txt'")
Example #59
0
def render_main(self, context, animation=False):
    # noinspection PyBroadException,PyBroadException
    try:
        # Get visible layers
        layers = []
        scene = context.scene
        for x in range(0, 20):
            if scene.layers[x] is True:
                layers.extend([x])

        # Get object list
        objlist = context.scene.objects
        # --------------------
        # Get resolution
        # --------------------
        scene = bpy.context.scene
        render_scale = scene.render.resolution_percentage / 100

        width = int(scene.render.resolution_x * render_scale)
        height = int(scene.render.resolution_y * render_scale)

        # ---------------------------------------
        # Get output path
        # ---------------------------------------
        ren_path = bpy.context.scene.render.filepath
        if len(ren_path) > 0:
            if ren_path.endswith(os.path.sep):
                initpath = os.path.realpath(ren_path) + os.path.sep
            else:
                (initpath, filename) = os.path.split(ren_path)
            outpath = os.path.join(initpath, "measureit_tmp_render.png")
        else:
            self.report({'ERROR'},
                        "MeasureIt: Unable to save temporary render image. Define a valid render path")
            return False

        # Get Render Image
        img = get_render_image(outpath)
        if img is None:
            self.report({'ERROR'},
                        "MeasureIt: Unable to save temporary render image. Define a valid render path")
            return False

        # -----------------------------
        # Calculate rows and columns
        # -----------------------------
        tile_x = 240
        tile_y = 216
        row_num = ceil(height / tile_y)
        col_num = ceil(width / tile_x)
        print("MeasureIt: Image divided in " + str(row_num) + "x" + str(col_num) + " tiles")

        # pixels out of visible area
        cut4 = (col_num * tile_x * 4) - width * 4  # pixels aout of drawing area
        totpixel4 = width * height * 4  # total pixels RGBA

        viewport_info = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)

        # Load image on memory
        img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)
        tex = img.bindcode

        # --------------------------------------------
        # Create output image (to apply texture)
        # --------------------------------------------
        if "measureit_output" in bpy.data.images:
            out_img = bpy.data.images["measureit_output"]
            if out_img is not None:
                out_img.user_clear()
                bpy.data.images.remove(out_img)

        out = bpy.data.images.new("measureit_output", width, height)
        tmp_pixels = [1] * totpixel4

        # --------------------------------
        # Loop for all tiles
        # --------------------------------
        for row in range(0, row_num):
            for col in range(0, col_num):
                buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
                bgl.glDisable(bgl.GL_SCISSOR_TEST)  # if remove this line, get blender screenshot not image
                bgl.glViewport(0, 0, tile_x, tile_y)

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

                # defines ortographic view for single tile
                x1 = tile_x * col
                y1 = tile_y * row
                bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y)

                # Clear
                bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
                bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

                bgl.glEnable(bgl.GL_TEXTURE_2D)
                bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

                # defines drawing area
                bgl.glBegin(bgl.GL_QUADS)

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

                bgl.glTexCoord2f(1.0, 0.0)
                bgl.glVertex2f(width, 0.0)

                bgl.glTexCoord2f(1.0, 1.0)
                bgl.glVertex2f(width, height)

                bgl.glTexCoord2f(0.0, 1.0)
                bgl.glVertex2f(0.0, height)

                bgl.glEnd()

                # -----------------------------
                # Loop to draw all lines
                # -----------------------------
                for myobj in objlist:
                    if myobj.hide is False:
                        if 'MeasureGenerator' in myobj:
                            # verify visible layer
                            for x in range(0, 20):
                                if myobj.layers[x] is True:
                                    if x in layers:
                                        op = myobj.MeasureGenerator[0]
                                        draw_segments(context, myobj, op, None, None)
                                    break

                if scene.measureit_rf is True:
                    bgl.glColor3f(1.0, 1.0, 1.0)
                    rfcolor = scene.measureit_rf_color
                    rfborder = scene.measureit_rf_border
                    rfline = scene.measureit_rf_line

                    bgl.glLineWidth(rfline)
                    bgl.glColor4f(rfcolor[0], rfcolor[1], rfcolor[2], rfcolor[3])

                    x1 = rfborder
                    x2 = width - rfborder
                    y1 = int(math.ceil(rfborder / (width / height)))
                    y2 = height - y1
                    draw_rectangle((x1, y1), (x2, y2))

                # --------------------------------
                # copy pixels to temporary area
                # --------------------------------
                bgl.glFinish()
                bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)  # read image data
                for y in range(0, tile_y):
                    # final image pixels position
                    p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4)
                    p2 = p1 + (tile_x * 4)
                    # buffer pixels position
                    b1 = y * width * 4
                    b2 = b1 + (tile_x * 4)

                    if p1 < totpixel4:  # avoid pixel row out of area
                        if col == col_num - 1:  # avoid pixel columns out of area
                            p2 -= cut4
                            b2 -= cut4

                        tmp_pixels[p1:p2] = buffer[b1:b2]

        # -----------------------
        # Copy temporary to final
        # -----------------------
        out.pixels = tmp_pixels[:]  # Assign image data
        img.gl_free()  # free opengl image memory

        # delete image
        img.user_clear()
        bpy.data.images.remove(img)
        # remove temp file
        os.remove(outpath)
        # reset
        bgl.glEnable(bgl.GL_SCISSOR_TEST)
        # -----------------------
        # restore opengl defaults
        # -----------------------
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        # Saves image
        if out is not None and (scene.measureit_render is True or animation is True):
            ren_path = bpy.context.scene.render.filepath
            filename = "mit_frame"
            if len(ren_path) > 0:
                if ren_path.endswith(os.path.sep):
                    initpath = os.path.realpath(ren_path) + os.path.sep
                else:
                    (initpath, filename) = os.path.split(ren_path)

            ftxt = "%04d" % scene.frame_current
            outpath = os.path.join(initpath, filename + ftxt + ".png")

            save_image(self, outpath, out)

        return True

    except:
        print("Unexpected error:" + str(sys.exc_info()))
        self.report({'ERROR'}, "MeasureIt: Unable to create render image")
        return False