コード例 #1
0
ファイル: hud.py プロジェクト: flossmanualsfr/peril-en-daiza
def write():
    """write on screen"""
    # retrieve timer
    global game_timer
    scene = logic.getCurrentScene()
    game_timer = int(active_camera["Timer"])
    catched = bamboo_counter["catched"]
    total = bamboo_counter["total"]
    vortex = panda.power
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    
    bgl.glColor4f(1, 1, 1, 1)
    
    # BLF drawing routine
    font_id = logic.font_id
    blf.size(font_id, int(18 * (width/dpi) * 0.06), dpi)
    blf.position(font_id, width*0.02, height*0.95, 0)
    if game_timer < 60:
        blf.draw(font_id, "{0} : {1:02d}".format(l_timer,game_timer))
    else:
        blf.draw(font_id, "{0} : {1}:{2:02d}".format(l_timer,game_timer//60,game_timer%60))
    blf.position(font_id, width*0.02, height*0.90, 0)
    blf.draw(font_id, "{0} : {1}".format(l_level, level))
    blf.position(font_id, width*0.02, height*0.85, 0)
    blf.draw(font_id, "{0} : {1} / {2}".format(l_score, catched, total))
    blf.position(font_id, width*0.02, height*0.80, 0)
    blf.draw(font_id, "{0} : {1}".format(l_vortex, vortex))
コード例 #2
0
	def redraw(self):

		drawregion = bpy.context.region

		rv3d = self.rv3ds[drawregion]
		vec = self.originvert.co.copy()
		vec.rotate(self.selobj.matrix_world)
		vec.rotate(self.selobj.matrix_world)
		self.space3d.cursor_location =  vec * self.selobj.matrix_world + self.selobj.matrix_world.to_translation()

		bgl.glColor3f(1.0, 1.0, 0)
		bgl.glBegin(bgl.GL_POLYGON)
		x, y = self.getscreencoords(Vector(self.originvert.co), drawregion, rv3d)
		bgl.glVertex2f(x-2, y-2)
		bgl.glVertex2f(x-2, y+2)
		bgl.glVertex2f(x+2, y+2)
		bgl.glVertex2f(x+2, y-2)
		bgl.glEnd()

		bgl.glColor3f(1, 1, 0.7)
		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glLoadIdentity()
		bgl.gluOrtho2D(0, self.region.width, 0, self.region.height)
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
		bgl.glLoadIdentity()
		blf.position(0, self.region.width/2 - 80, self.region.height - 20, 0)
		blf.size(0, 12, 72)
		blf.draw(0, "FastOrigin :  Enter confirms - ESC cancels")
コード例 #3
0
def write():
    """
    Write the name of all active objects on Screen
    """
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, windowWidth, 0, windowHeight)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    cam = scene.active_camera

    for obj in passive_objects.active_objects():
        # test if the object is in the view frustum
        if cam.pointInsideFrustum(obj.worldPosition):
            pos = cam.getScreenPosition(obj)

            blf.size(font_id, int(windowWidth * 0.02), 72)
            # draw a black shadow to increase contrast with white parts
            blf.enable(font_id, blf.SHADOW)
            blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)
            blf.position(font_id, pos[0] * windowWidth,
                         (1 - pos[1]) * windowHeight, 0)
            blf.draw(font_id, obj.name)
コード例 #4
0
    def redraw(self):

        drawregion = bpy.context.region

        rv3d = self.rv3ds[drawregion]
        vec = self.originvert.co.copy()
        vec.rotate(self.selobj.matrix_world)
        vec.rotate(self.selobj.matrix_world)
        self.space3d.cursor_location = vec * self.selobj.matrix_world + self.selobj.matrix_world.to_translation(
        )

        bgl.glColor3f(1.0, 1.0, 0)
        bgl.glBegin(bgl.GL_POLYGON)
        x, y = self.getscreencoords(Vector(self.originvert.co), drawregion,
                                    rv3d)
        bgl.glVertex2f(x - 2, y - 2)
        bgl.glVertex2f(x - 2, y + 2)
        bgl.glVertex2f(x + 2, y + 2)
        bgl.glVertex2f(x + 2, y - 2)
        bgl.glEnd()

        bgl.glColor3f(1, 1, 0.7)
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, self.region.width, 0, self.region.height)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()
        blf.position(0, self.region.width / 2 - 80, self.region.height - 20, 0)
        blf.size(0, 12, 72)
        blf.draw(0, "FastOrigin :  Enter confirms - ESC cancels")
コード例 #5
0
    def draw(self):
        self.allocate(
            Rect(self.margin.x, self.margin.y,
                 self._render.getWindowWidth() - self.margin.sx,
                 self._render.getWindowHeight() - self.margin.sy))
        self.layout()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, self._render.getWindowWidth(), 0,
                       self._render.getWindowHeight())
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        bgl.glPushMatrix()
        bgl.glTranslatef(self.margin.x, self.margin.h, 0)

        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_DEPTH)
        bgl.glDisable(bgl.GL_LIGHTING)

        Widget.draw(self)

        bgl.glPopMatrix()
コード例 #6
0
def writeMessageOnScreen():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    font_id = logic.font_id
    blf.position(font_id, (width * 0.02), (height * 0.05), 0)
    blf.size(font_id, 35, 50)
    bgl.glColor4f(1, 0, 0, 1)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 1, 0, 1)
    blf.position(font_id, (width * 0.02), (height * 0.15), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 0, 1, 1)
    blf.position(font_id, (width * 0.02), (height * 0.20), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")
コード例 #7
0
ファイル: effect.py プロジェクト: theirishduck/blender-zombie
    def fx():
        width = bge.render.getWindowWidth()
        height = bge.render.getWindowHeight()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, width, 0, height)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.8, 0.0, 0.0, 0.1)
        bgl.glRecti(0, 0, width, height)
        # bgl.glBegin(bgl.GL_QUADS)
        # bgl.glVertex2i(0, 0)
        # bgl.glVertex2i(width, 0)
        # bgl.glVertex2i(width, height)
        # bgl.glVertex2i(0, height)

        # bgl.glVertex2f(0.0, 0.0)
        # bgl.glVertex2f(1.0, 0.0)
        # bgl.glVertex2f(1.0, 1.0)
        # bgl.glVertex2f(0.0, 1.0)

        # bgl.glEnd()
        bgl.glDisable(bgl.GL_BLEND)
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()
def write_interaction_status():
    """
    Write the interaction status on Screen
    The status is stored in a property
    """
    cam = blenderapi.scene().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]

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, windowWidth, 0, windowHeight)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    blf.size(font_id, int(windowHeight * 0.04), 72)
    # draw a black shadow around the text
    blf.enable(font_id, blf.SHADOW)
    blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)
    blf.position(font_id, windowWidth * 0.4, windowHeight * 0.4, 0)
    blf.draw(font_id, hand['Status'])
コード例 #10
0
def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    #bgl.glColor(1,1,1,1)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF drawing routine
    font_id = logic.font_id
    RED = (1, 0, 0, 1)
    pcol = ("Blue ", RED)
    #blf.color(font_id, 1, 1, 0, 0.5)
    blf.blur(font_id, 500)
    blf.rotation(font_id, 90)
    blf.position(font_id, (width * 0.5), (height * 0.5), 0.5)
    blf.size(font_id, 20, 100)
    blf.draw(font_id, "Hello World1")
    blf.size(font_id, 50, 72)
    blf.position(font_id, (width * 0.0), (height * 0.5), 0.5)
    blf.draw(font_id, "Hello World2")
コード例 #11
0
ファイル: effect.py プロジェクト: TripleSnail/blender-zombie
    def fx():
        width = bge.render.getWindowWidth()
        height = bge.render.getWindowHeight()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, width, 0, height)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()


        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.8, 0.0, 0.0, 0.1)
        bgl.glRecti(0, 0, width, height)
        # bgl.glBegin(bgl.GL_QUADS)
        # bgl.glVertex2i(0, 0)
        # bgl.glVertex2i(width, 0)
        # bgl.glVertex2i(width, height)
        # bgl.glVertex2i(0, height)

        # bgl.glVertex2f(0.0, 0.0)
        # bgl.glVertex2f(1.0, 0.0)
        # bgl.glVertex2f(1.0, 1.0)
        # bgl.glVertex2f(0.0, 1.0)



        # bgl.glEnd()
        bgl.glDisable(bgl.GL_BLEND)
コード例 #12
0
def writeMessageOnScreen():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    font_id = logic.font_id
    blf.position(font_id, (width * 0.02), (height * 0.05), 0)
    blf.size(font_id, 35, 50)
    bgl.glColor4f(1, 0, 0, 1)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 1, 0, 1)
    blf.position(font_id, (width * 0.02), (height * 0.15), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")

    bgl.glColor4f(0, 0, 1, 1)
    blf.position(font_id, (width * 0.02), (height * 0.20), 0)
    blf.size(font_id, 25, 50)
    blf.draw(font_id, "Hello World!")
コード例 #13
0
ファイル: interaction.py プロジェクト: sylvestre/morse
def write_interaction_status():
    """
    Write the interaction status on Screen
    The status is stored in a property
    """
    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]
    
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, windowWidth, 0, windowHeight)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    
    blf.size(font_id, int(windowHeight*0.04), 72)
    # draw a black shadow around the text
    blf.enable(font_id, blf.SHADOW)
    blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)
    blf.position(font_id, windowWidth*0.4, windowHeight*0.4,0)
    blf.draw(font_id, hand['Status'])
コード例 #14
0
ファイル: interaction.py プロジェクト: sylvestre/morse
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()
コード例 #15
0
    def draw(self):
        if self.visible == False: return

        module.post_draw_step += 1

        height = render.getWindowHeight()
        width = render.getWindowWidth()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, width, 0, height)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        # Enable textures
        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)
        bgl.glAlphaFunc(bgl.GL_SRC_ALPHA, 1)

        # Bind the texture
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, self._tex_id)

        # Fix position
        w, h = self._size
        bgl.glTranslatef(0, -h, 1)

        #MipLevel
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_BASE_LEVEL, 0)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAX_LEVEL, 0)
        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)

        # Draw the textured quad
        bgl.glColor4f(*self.color)

        bgl.glBegin(bgl.GL_QUADS)
        self.calculate_glposition()
        for i in range(4):
            bgl.glTexCoord2f(self.texco[i][0], self.texco[i][1])
            bgl.glVertex2f(self.gl_position[i][0], self.gl_position[i][1])
        bgl.glEnd()

        bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_TEXTURE_2D)

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
コード例 #16
0
def draw_names():
    # Get font id to use
    font_id = logic.font_id

    # Collect viewport information
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # Setup the OpenGL matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)

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

    # Get the camera
    scene = logic.getCurrentScene()
    camera = scene.active_camera

    # draw the name only for objects (not for lamps or camera)
    for object in [
            i for i in scene.objects if i.__class__ == types.KX_GameObject
    ]:
        # Calculate x and y
        screen_coord = camera.getScreenPosition(object)
        x = screen_coord[0] * render.getWindowWidth()
        y = render.getWindowHeight() - (screen_coord[1] *
                                        render.getWindowHeight())

        # Center the x
        text_width, text_height = blf.dimensions(0, object.name)
        x -= text_width / 2

        # Calculate the amount to scale the font
        distance = camera.getDistanceTo(object)

        if FAR - distance > 0:
            scale = (FAR - distance) / FAR
        else:
            scale = 0

        # Only draw if we'll be able to see it
        if scale:
            blf.size(font_id, int(FONT_SIZE * scale), 72)
            blf.position(font_id, x, y, 0)
            blf.draw(font_id, object.name)

    # Reset the matrices
    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
コード例 #17
0
ファイル: window.py プロジェクト: Hubber116sx/BGECore
	def draw(self):
		if self.visible == False: return
		
		module.post_draw_step += 1
		
		height = render.getWindowHeight()
		width = render.getWindowWidth()
	
		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glLoadIdentity()
		bgl.gluOrtho2D(0, width, 0, height)
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
		bgl.glLoadIdentity()
	
		# Enable textures
		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)
		bgl.glAlphaFunc(bgl.GL_SRC_ALPHA, 1)

		# Bind the texture
		bgl.glBindTexture(bgl.GL_TEXTURE_2D, self._tex_id)

		# Fix position
		w, h = self._size
		bgl.glTranslatef(0, -h, 1)

		#MipLevel
		bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_BASE_LEVEL, 0);
		bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAX_LEVEL, 0);
		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);
		
		# Draw the textured quad
		bgl.glColor4f(*self.color)

		bgl.glBegin(bgl.GL_QUADS)
		self.calculate_glposition()
		for i in range(4):
			bgl.glTexCoord2f(self.texco[i][0], self.texco[i][1])
			bgl.glVertex2f(self.gl_position[i][0], self.gl_position[i][1])
		bgl.glEnd()

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

		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glPopMatrix()
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
コード例 #18
0
ファイル: display.py プロジェクト: merlinwu/phobos
def draw_callback_px(self, context):
    # define common variables
    region, rv3d = getRegionData()
    active = context.object
    selected = context.selected_objects
    wm = context.window_manager

    # ----- 3D Drawing -----
    bgl.glEnable(bgl.GL_BLEND)

    if active:
        if 'submechanism/spanningtree' in context.object:
            draw_submechanism(context.object['submechanism/spanningtree'])

    if len(selected) > 0:
        for j in [o for o in selected if o.phobostype == 'link']:
            draw_joint(j)

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    # ----- 2D Drawing -----
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, bpy.context.region.width, 0, bpy.context.region.height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    bgl.glEnable(bgl.GL_BLEND)

    # progress bar
    if context.window_manager.progress not in [0, 1]:
        draw_progressbar(wm.progress)
    # log messages
    for m in range(wm.phobos_msg_count):
        opacity = 1.0
        if 1 >= m <= wm.phobos_msg_offset - 1 or m >= wm.phobos_msg_count - 2:
            opacity = 0.5
        if wm.phobos_msg_offset > 1 > m or m >= wm.phobos_msg_count - 1:
            opacity = 0.1
        try:
            msg = messages[m + wm.phobos_msg_offset]
            draw_message(msg['text'],
                         msg['type'],
                         m,
                         opacity,
                         offset=wm.phobos_msg_offset)
        except IndexError:
            pass

    bgl.glDisable(bgl.GL_BLEND)
コード例 #19
0
	def text( self, text ):
		if self.configured is True:
			width = bge.render.getWindowWidth()
			height = bge.render.getWindowHeight()
			bgl.glMatrixMode(bgl.GL_PROJECTION)
			bgl.glLoadIdentity()
			bgl.gluOrtho2D(0, width, 0, height)
			bgl.glMatrixMode(bgl.GL_MODELVIEW)
			bgl.glLoadIdentity()
			font_id = self.font_id
			blf.position( font_id, 20, 20, 0)
			blf.size( font_id, 300, 300)
			blf.draw( font_id, "Hello World")
コード例 #20
0
 def text(self, text):
     if self.configured is True:
         width = bge.render.getWindowWidth()
         height = bge.render.getWindowHeight()
         bgl.glMatrixMode(bgl.GL_PROJECTION)
         bgl.glLoadIdentity()
         bgl.gluOrtho2D(0, width, 0, height)
         bgl.glMatrixMode(bgl.GL_MODELVIEW)
         bgl.glLoadIdentity()
         font_id = self.font_id
         blf.position(font_id, 20, 20, 0)
         blf.size(font_id, 300, 300)
         blf.draw(font_id, "Hello World")
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()
コード例 #22
0
ファイル: interaction.py プロジェクト: sylvestre/morse
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()
コード例 #23
0
def draw_console_gl():
    '''draw console with bgl and blf, line by line'''
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, render.getWindowWidth(), 0, render.getWindowHeight())
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    # text BLF drawing routine
    for r in logic.rows:
        bgl.glColor4f(r['color'][0], r['color'][1], r['color'][2],
                      1 - r['alpha'])
        blf.position(r['id'], *r['pos'])
        blf.size(r['id'], *r['size'])
        blf.draw(r['id'], r['text'])
コード例 #24
0
ファイル: text.py プロジェクト: TripleSnail/blender-zombie
def write():
    width = bge.render.getWindowWidth()
    height = bge.render.getWindowHeight()

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    font_id = bge.logic.font_id

    for text_obj in text_objects:
        blf.position(font_id, width * text_obj.px , height * text_obj.py, 0)
        blf.size(font_id, text_obj.size, DPI)
        blf.draw(font_id, text_obj.text)
コード例 #25
0
    def _drawSelectionBox(self):

        quad = self._getScreenQuad()

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

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

        bgl.glColor3f(1, 0, 0)
        bgl.glBegin(bgl.GL_LINE_LOOP)
        for p in quad:
            bgl.glVertex2f(p.x, p.y)
        bgl.glEnd()
コード例 #26
0
def write():
    width = bge.render.getWindowWidth()
    height = bge.render.getWindowHeight()

    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    font_id = bge.logic.font_id

    for text_obj in text_objects:
        blf.position(font_id, width * text_obj.px, height * text_obj.py, 0)
        blf.size(font_id, text_obj.size, DPI)
        blf.draw(font_id, text_obj.text)
コード例 #27
0
def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF drawing routine
    font_id = logic.font_id
    blf.position(font_id, (width * 0.2), (height * 0.3), 0)
    blf.size(font_id, 50, 72)
    blf.draw(font_id, "Hello World")
コード例 #28
0
def write():
    """write on screen - it runs every frame"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF fun
    font_id = logic.font_id
    blf.position(font_id, (width*0.2), (height*0.3), 0)
    blf.size(font_id, 50, 72)
    blf.draw(font_id, logic.text["text"])
コード例 #29
0
def write():
	''' Uses text buffer for rendering stuff on screen
	
	Text buffer can be found from logic.text_buffer
	Each value in buffer is a hash, containing text, timeout and start_time
	start time is set by me, not you
	'''

	"""write on screen"""
	width = render.getWindowWidth()
	height = render.getWindowHeight()

	# OpenGL setup
	bgl.glMatrixMode(bgl.GL_PROJECTION)
	bgl.glLoadIdentity()
	bgl.gluOrtho2D(0, width, 0, height)
	bgl.glMatrixMode(bgl.GL_MODELVIEW)
	bgl.glLoadIdentity()

	show_das_points()

	if logic.text_buffer == None or len(logic.text_buffer) == 0:
		return
	
	text = ''
	
	# has the current value start time
	if 'start_time' in logic.text_buffer[0]:
		start_time = logic.text_buffer[0]['start_time']
		current_time = current_milli_time()
		timeout = logic.text_buffer[0]['timeout']
		if start_time + timeout < current_milli_time():
			logic.text_buffer.pop(0)
		else:
			text = logic.text_buffer[0]['text']
	else:
		logic.text_buffer[0]['start_time'] = current_milli_time()
		text = logic.text_buffer[0]['text']

	# BLF drawing routine
	font_id = logic.font_id
	blf.position(font_id, (width * 0.25), (height * 0.5), 0)
	blf.size(font_id, 24, 72)
	blf.draw(font_id, text)
コード例 #30
0
ファイル: text.py プロジェクト: leomuona/RBS2013
def write():
    ''' Uses text buffer for rendering stuff on screen
	
	Text buffer can be found from logic.text_buffer
	Each value in buffer is a hash, containing text, timeout and start_time
	start time is set by me, not you
	'''
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    show_das_points()

    if logic.text_buffer == None or len(logic.text_buffer) == 0:
        return

    text = ''

    # has the current value start time
    if 'start_time' in logic.text_buffer[0]:
        start_time = logic.text_buffer[0]['start_time']
        current_time = current_milli_time()
        timeout = logic.text_buffer[0]['timeout']
        if start_time + timeout < current_milli_time():
            logic.text_buffer.pop(0)
        else:
            text = logic.text_buffer[0]['text']
    else:
        logic.text_buffer[0]['start_time'] = current_milli_time()
        text = logic.text_buffer[0]['text']

    # BLF drawing routine
    font_id = logic.font_id
    blf.position(font_id, (width * 0.25), (height * 0.5), 0)
    blf.size(font_id, 24, 72)
    blf.draw(font_id, text)
コード例 #31
0
def write_interaction_status():
    """
    Write the interaction status on Screen
    The status is stored in a property
    """
    hand = objects["Hand_Grab.R"]

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, windowWidth, 0, windowHeight)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    blf.size(font_id, int(windowHeight * 0.04), 72)
    # draw a black shadow around the text
    blf.enable(font_id, blf.SHADOW)
    blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)
    blf.position(font_id, windowWidth * 0.4, windowHeight * 0.4, 0)
    blf.draw(font_id, hand["Status"])
コード例 #32
0
def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    
    bgl.glColor4f(1, 1, 1, 1)
    
    cam = logic.getCurrentScene().active_camera
    t = cam["Timer"]
    c = timer - t
    bgl.glColor4f(1, 1, 1, c)
    if cam["Switch"]:
        cam["Index"] += 1
        cam["Timer"] = 0
        cam["Switch"] = False
    # BLF drawing routine
    font_id = logic.font_id
    font_id_italic = logic.font_id_italic
    blf.position(font_id, width*0.03, height * 0.05, 0)
    blf.position(font_id_italic, width*0.03, height * 0.05, 0)
    blf.size(font_id, int(18 * (width/dpi) * 0.062), dpi)
    blf.size(font_id_italic, int(18 * (width/dpi) * 0.062), dpi)
    if cam["Index"] < 4:
        blf.draw(font_id, text[cam["Index"]])
    elif cam["Index"] < len(text):
        blf.draw(font_id_italic, text[cam["Index"]])
    
    # skip
    if cam["Index"] < 1:
        bgl.glColor4f(0.5, 0.5, 0.5, c)
        blf.position(font_id, width*0.02, height*0.9, 0)

        blf.draw(font_id, skip)
コード例 #33
0
ファイル: Text.py プロジェクト: tailscreatesstuff32/DemoTuto
    def write(self):
        # OpenGL setup
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, self.renderSize.x, 0, self.renderSize.y)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        # BLF drawing routine
        if self.normPos == 1:
            blf.position(
                self.fontID, (self.renderSize.x * self.position.x),
                self.renderSize.y - (self.renderSize.y * self.position.y), 0)
        else:
            blf.position(self.fontID, self.position.x,
                         self.renderSize.y - self.position.y, 0)

        if self.normSize == 1:
            blf.size(self.fontID, int(self.renderSize.x * self.size.x),
                     int(self.renderSize.y * self.size.y))
        else:
            blf.size(self.fontID, int(self.size.x), int(self.size.y))
        blf.draw(self.fontID, self.text)
コード例 #34
0
ファイル: Tutorial_Script.py プロジェクト: DefaultUser/morse
def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF drawing routine
    blf.size(font_id, height // 40, 72)
    data = parse_file.read_file()
    data = data.splitlines()
    linePosition = height * 0.8
    for str in data:
        str_len = len(str)
        blf.position(font_id, (width * 0.05), linePosition, 0)
        blf.enable(font_id, blf.SHADOW)
        blf.shadow(font_id, 0, 1.0, 0.2, 0.0, 1.0)
        blf.draw(font_id, str)
        linePosition -= height * 0.05
コード例 #35
0
ファイル: Tutorial_Script.py プロジェクト: DefaultUser/morse
def write():
    """write on screen"""
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()

    # BLF drawing routine
    blf.size(font_id, height//40, 72)
    data = parse_file.read_file()
    data = data.splitlines()
    linePosition = height * 0.8
    for str in data:
        str_len = len(str)
        blf.position(font_id, (width * 0.05), linePosition, 0)
        blf.enable(font_id, blf.SHADOW)
        blf.shadow(font_id, 0, 1.0, 0.2, 0.0, 1.0)
        blf.draw(font_id,str)
        linePosition -= height * 0.05
コード例 #36
0
ファイル: show_objects.py プロジェクト: DefaultUser/morse
def write():
    """
    Write the name of all active objects on Screen
    """
    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, windowWidth, 0, windowHeight)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    
    cam = scene.active_camera

    for obj in passive_objects.active_objects():
        # test if the object is in the view frustum
        if cam.pointInsideFrustum(obj.worldPosition):
            pos = cam.getScreenPosition(obj)
    
            blf.size(font_id, int(windowWidth * 0.02), 72)
            # draw a black shadow to increase contrast with white parts
            blf.enable(font_id, blf.SHADOW)
            blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)
            blf.position(font_id, pos[0]*windowWidth, (1 - pos[1])*windowHeight,0)
            blf.draw(font_id, obj.name)
コード例 #37
0
    def execute(self, refholder):
        # pass
        tr = self.nodeTree.properties.TextureResolution
        print("begining execution " + str(tr))
        # compute A'
        mask = np.array([[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]])
        # Input data pixels
        A = self.inputs[0].getPixels()
        B = self.inputs[1].getPixels()

        # print(A)

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

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

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

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

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

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

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

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

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

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

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

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

                bgl.glBegin(bgl.GL_TRIANGLES)

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

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

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

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

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

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

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

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

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

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

        #restore the state so blender wont break
        bgl.glEnable(bgl.GL_SCISSOR_TEST)
        bgl.glUseProgram(self.rdData[self.name]["prev_program"][0])
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
コード例 #38
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
コード例 #39
0
ファイル: label.py プロジェクト: Hubber116sx/BGECore
	def draw(self):
		if self.visible == False: return
		module.post_draw_step += 1
		
		cam = self.scene.active_camera
		orth = cam.ortho_scale
		
		height = render.getWindowHeight()
		width = render.getWindowWidth()
		near = cam.near
		far = cam.far
		h = cam.worldPosition.z
		font_id = Label._fontname_id[self._font]
		unit = width/orth
		self._glunit = unit
		rpos = self._position - cam.worldPosition
		
		bgl.glMatrixMode(bgl.GL_PROJECTION)
		bgl.glLoadIdentity()
		bgl.gluOrtho2D(0, width, 0, height)
		bgl.glMatrixMode(bgl.GL_MODELVIEW)
		bgl.glLoadIdentity()
		
		bgl.glEnable(bgl.GL_BLEND)
		bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
		bgl.glAlphaFunc(bgl.GL_SRC_ALPHA, 1)
		
		#Z AXIS
		oh = (far-near)/2
		ortho_unit = 1/oh
		dh = oh

		pos = list([width/2+rpos[0]*unit, height/2+rpos[1]*unit, dh*ortho_unit + rpos[2]*ortho_unit])
		if self._lastscale != self.scale or True:
			blf.size(font_id, int(self.scale.x*unit), 72)
		else:
			if self._lastorth != orth:
				sc = (float(self._lastorth) / float(orth)) * self.scale.x
				bgl.glScalef(sc,sc,1)
				print(str(self._lastorth) + " " + str(orth))
				pos[0] /= sc
				pos[1] /= sc
				
			else:
				self._lastorth = orth
		
		x, y = blf.dimensions(font_id, self._text) #NOTE: Always after blf.size()
		
		if self.align == ALIGN_CENTER:
			pos[0] -= (x)/2 * math.cos(self._rotation.z)
			pos[1] -= x/2 * math.sin(self._rotation.z)
		if self.align == ALIGN_RIGHT:
			pos[0] -= x * math.cos(self._rotation.z)
			pos[1] -= x * math.sin(self._rotation.z)
			
		if self.middle_height == True:
			pos[0] -= y/4 * math.sin(self._rotation.z)
			pos[1] -= y/4 * math.cos(self._rotation.z)
		
		blf.position(font_id, pos[0], pos[1], pos[2])
		blf.enable(font_id, blf.ROTATION)
		if self.rotation.z > 0.01 or self.rotation.z < -0.01:
			blf.rotation(font_id, self._rotation.z)
		else:
			blf.rotation(font_id, 0)
		
		if self.shadow == True:
			blf.position(font_id, pos[0]+self.shadow_offset[0], pos[1]+self.shadow_offset[1], pos[2])
			bgl.glColor4f(*self.shadow_color)
			blf.blur(font_id, self.shadow_blur)
			blf.draw(font_id, self._text)
			blf.position(font_id, pos[0], pos[1], pos[2])
			
		bgl.glColor4f(*self._color)
		blf.blur(font_id, self.blur)
		blf.draw(font_id, self._text)
		
		blf.disable(font_id, blf.ROTATION)
		
		self._lastscale = self.scale
コード例 #40
0
    def draw(self):
        if self.visible == False: return
        module.post_draw_step += 1

        cam = self.scene.active_camera
        orth = cam.ortho_scale

        height = render.getWindowHeight()
        width = render.getWindowWidth()
        near = cam.near
        far = cam.far
        h = cam.worldPosition.z
        font_id = Label._fontname_id[self._font]
        unit = width / orth
        self._glunit = unit
        rpos = self._position - cam.worldPosition

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, width, 0, height)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
        bgl.glAlphaFunc(bgl.GL_SRC_ALPHA, 1)

        #Z AXIS
        oh = (far - near) / 2
        ortho_unit = 1 / oh
        dh = oh

        pos = list([
            width / 2 + rpos[0] * unit, height / 2 + rpos[1] * unit,
            dh * ortho_unit + rpos[2] * ortho_unit
        ])
        if self._lastscale != self.scale or True:
            blf.size(font_id, int(self.scale.x * unit), 72)
        else:
            if self._lastorth != orth:
                sc = (float(self._lastorth) / float(orth)) * self.scale.x
                bgl.glScalef(sc, sc, 1)
                print(str(self._lastorth) + " " + str(orth))
                pos[0] /= sc
                pos[1] /= sc

            else:
                self._lastorth = orth

        x, y = blf.dimensions(font_id,
                              self._text)  #NOTE: Always after blf.size()

        if self.align == ALIGN_CENTER:
            pos[0] -= (x) / 2 * math.cos(self._rotation.z)
            pos[1] -= x / 2 * math.sin(self._rotation.z)
        if self.align == ALIGN_RIGHT:
            pos[0] -= x * math.cos(self._rotation.z)
            pos[1] -= x * math.sin(self._rotation.z)

        if self.middle_height == True:
            pos[0] -= y / 4 * math.sin(self._rotation.z)
            pos[1] -= y / 4 * math.cos(self._rotation.z)

        blf.position(font_id, pos[0], pos[1], pos[2])
        blf.enable(font_id, blf.ROTATION)
        if self.rotation.z > 0.01 or self.rotation.z < -0.01:
            blf.rotation(font_id, self._rotation.z)
        else:
            blf.rotation(font_id, 0)

        if self.shadow == True:
            blf.position(font_id, pos[0] + self.shadow_offset[0],
                         pos[1] + self.shadow_offset[1], pos[2])
            bgl.glColor4f(*self.shadow_color)
            blf.blur(font_id, self.shadow_blur)
            blf.draw(font_id, self._text)
            blf.position(font_id, pos[0], pos[1], pos[2])

        bgl.glColor4f(*self._color)
        blf.blur(font_id, self.blur)
        blf.draw(font_id, self._text)

        blf.disable(font_id, blf.ROTATION)

        self._lastscale = self.scale
コード例 #41
0
    def render(self, context):
        # needed???
        if context.region.id == self.region_id:
            # just hide the cursor...
            context.space_data.cursor_location = [0.0, 0.0, 10.0]
            context.space_data.region_3d.view_matrix = Matrix.Identity(4)
            
            w = context.region.width
            h = context.region.height
            
            x1, x2, x3, x4, y1, y2, y3, y4 = self.grid(w, h)
                       
            bgl.glMatrixMode(bgl.GL_PROJECTION)
            bgl.glLoadIdentity()
            bgl.gluOrtho2D(0, w, 0, h)
            bgl.glMatrixMode(bgl.GL_MODELVIEW)
            bgl.glLoadIdentity()
            
            bgl.glColor3f(*self.COLOR_BOARD)
            bgl.glLineWidth(2.0)
            bgl.glBegin(bgl.GL_LINES)
            for x in (x1, x2, x3, x4):
                bgl.glVertex3f(x, y1, 0.0)
                bgl.glVertex3f(x, y4, 0.0)
            for y in (y1, y2, y3, y4):
                bgl.glVertex3f(x1, y, 0.0)
                bgl.glVertex3f(x4, y, 0.0)
            bgl.glEnd()

            xs = (x1, x2, x3, x4)
            ys = (y1, y2, y3, y4)
            
            bgl.glLineWidth(8.0)
            bgl.glBegin(bgl.GL_LINES)
            for i in range(3):
                for j in range(3):
                    c = self.board[i][j]
                    xa = xs[i]
                    xb = xs[i + 1]
                    ya = ys[j]
                    yb = ys[j + 1]

                    if c == self.PLAYER:
                        if self.computer_has_x:
                            self.drawO(xa, xb, ya, yb)
                        else:
                            self.drawX(xa, xb, ya, yb)
                    elif c == self.COMPUTER:
                        if self.computer_has_x:
                            self.drawX(xa, xb, ya, yb)
                        else:
                            self.drawO(xa, xb, ya, yb)
            bgl.glEnd()

            bgl.glLineWidth(1.0)
            bgl.glColor3f(*self.COLOR_FONT)

            xp, yp = self.fontPosition(w, h)
            blf.position(0, xp, yp, 0)
            blf.size(0, 50, 72)

            if self.winner == self.COMPUTER:
                blf.draw(0, "You loose!")

            elif self.winner == self.PLAYER:
                blf.draw(0, "You win!")

            elif self.round == self.NONE:
                blf.draw(0, "Draw.")
コード例 #42
0
ファイル: interaction.py プロジェクト: sylvestre/morse
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()
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 = blenderapi.scene().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()
コード例 #44
0
    def render(self, context):
        # needed???
        if context.region.id == self.region_id:
            # just hide the cursor...
            context.space_data.cursor_location = [0.0, 0.0, 10.0]
            context.space_data.region_3d.view_matrix = Matrix.Identity(4)

            w = context.region.width
            h = context.region.height

            x1, x2, x3, x4, y1, y2, y3, y4 = self.grid(w, h)

            bgl.glMatrixMode(bgl.GL_PROJECTION)
            bgl.glLoadIdentity()
            bgl.gluOrtho2D(0, w, 0, h)
            bgl.glMatrixMode(bgl.GL_MODELVIEW)
            bgl.glLoadIdentity()

            bgl.glColor3f(*self.COLOR_BOARD)
            bgl.glLineWidth(2.0)
            bgl.glBegin(bgl.GL_LINES)
            for x in (x1, x2, x3, x4):
                bgl.glVertex3f(x, y1, 0.0)
                bgl.glVertex3f(x, y4, 0.0)
            for y in (y1, y2, y3, y4):
                bgl.glVertex3f(x1, y, 0.0)
                bgl.glVertex3f(x4, y, 0.0)
            bgl.glEnd()

            xs = (x1, x2, x3, x4)
            ys = (y1, y2, y3, y4)

            bgl.glLineWidth(8.0)
            bgl.glBegin(bgl.GL_LINES)
            for i in range(3):
                for j in range(3):
                    c = self.board[i][j]
                    xa = xs[i]
                    xb = xs[i + 1]
                    ya = ys[j]
                    yb = ys[j + 1]

                    if c == self.PLAYER:
                        if self.computer_has_x:
                            self.drawO(xa, xb, ya, yb)
                        else:
                            self.drawX(xa, xb, ya, yb)
                    elif c == self.COMPUTER:
                        if self.computer_has_x:
                            self.drawX(xa, xb, ya, yb)
                        else:
                            self.drawO(xa, xb, ya, yb)
            bgl.glEnd()

            bgl.glLineWidth(1.0)
            bgl.glColor3f(*self.COLOR_FONT)

            xp, yp = self.fontPosition(w, h)
            blf.position(0, xp, yp, 0)
            blf.size(0, 50, 72)

            if self.winner == self.COMPUTER:
                blf.draw(0, "You loose!")

            elif self.winner == self.PLAYER:
                blf.draw(0, "You win!")

            elif self.round == self.NONE:
                blf.draw(0, "Draw.")
コード例 #45
0
ファイル: utils.py プロジェクト: brendanaaa/Learnbgame
def generate_icon(name, verts=None, faces=None, coll="shape_types"):
    pcoll = preview_collections[coll]
    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
コード例 #46
0
# Load image on memory
img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)
tex = img.bindcode

# Create output image (to apply texture)
out = bpy.data.images.new("output", WIDTH, HEIGHT)
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, WIDTH, HEIGHT)

bgl.glMatrixMode(bgl.GL_PROJECTION)
bgl.glLoadIdentity()
bgl.gluOrtho2D(0, WIDTH, 0, HEIGHT)

#
bgl.glLineWidth(10)
bgl.glBegin(bgl.GL_LINES)

bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
#bgl.glTexCoord2f(0.0, 0.0)
bgl.glVertex2f(0.0, 0.0)
#bgl.glTexCoord2f(1.0, 1.0)
bgl.glVertex2f(WIDTH, HEIGHT)

bgl.glEnd()

bgl.glLineWidth(1)
bgl.glColor4f(1, 1.0, 0.0, 1)
コード例 #47
0
ファイル: utils.py プロジェクト: michax/perfect_shape
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
コード例 #48
0
    def render_main(self, context, objlist, animation=False):
        # noinspection PyBroadException,PyBroadException
        # Save old info
        scene = context.scene
        render = scene.render
        settings = render.image_settings
        depth = settings.color_depth
        settings.color_depth = '8'
        # noinspection PyBroadException
        try:

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

            # --------------------
            # Get resolution
            # --------------------
            render_scale = render.resolution_percentage / 100

            width = int(render.resolution_x * render_scale)
            height = int(render.resolution_y * render_scale)
            # ---------------------------------------
            # Get output path
            # ---------------------------------------
            temp_path = path.realpath(bpy.app.tempdir)
            if len(temp_path) > 0:
                outpath = path.join(temp_path, "archipack_tmp_render.png")
            else:
                self.report({
                    'ERROR'
                }, "Archipack: Unable to save temporary render image. Define a valid temp path"
                            )
                settings.color_depth = depth
                return False

            # Get Render Image
            img = self.get_render_image(outpath)
            if img is None:
                self.report({
                    'ERROR'
                }, "Archipack: Unable to save temporary render image. Define a valid temp path"
                            )
                settings.color_depth = depth
                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("Archipack: 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)

            # 2.77 API change
            if bpy.app.version >= (2, 77, 0):
                tex = img.bindcode[0]
            else:
                tex = img.bindcode

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

            out = bpy.data.images.new("archipack_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 o, d in objlist:
                        if o.hide is False:
                            # verify visible layer
                            for x in range(0, 20):
                                if o.layers[x] is True:
                                    if x in layers:
                                        context.scene.objects.active = o
                                        # print("%s: %s" % (o.name, d.manip_stack))
                                        manipulators = d.manip_stack
                                        if manipulators is not None:
                                            for m in manipulators:
                                                if m is not None:
                                                    m.draw_callback(
                                                        m,
                                                        context,
                                                        render=True)
                                    break

                    # -----------------------------
                    # Loop to draw all debug
                    # -----------------------------
                    """
                    if scene.archipack_debug is True:
                        selobj = bpy.context.selected_objects
                        for myobj in selobj:
                            if scene.archipack_debug_vertices is True:
                                draw_vertices(context, myobj, None, None)
                            if scene.archipack_debug_faces is True or scene.archipack_debug_normals is True:
                                draw_faces(context, myobj, None, None)
                    """
                    """
                    if scene.archipack_rf is True:
                        bgl.glColor3f(1.0, 1.0, 1.0)
                        rfcolor = scene.archipack_rf_color
                        rfborder = scene.archipack_rf_border
                        rfline = scene.archipack_rf_line

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

                        x1 = rfborder
                        x2 = width - rfborder
                        y1 = int(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
            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.archipack_render is True or animation is True):
                ren_path = bpy.context.scene.render.filepath
                filename = "ap_frame"
                if len(ren_path) > 0:
                    if ren_path.endswith(path.sep):
                        initpath = path.realpath(ren_path) + path.sep
                    else:
                        (initpath, filename) = path.split(ren_path)

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

                self.save_image(outpath, out)

            settings.color_depth = depth
            return True

        except:
            settings.color_depth = depth
            print("Unexpected error:" + str(exc_info()))
            self.report({
                'ERROR'
            }, "Archipack: Unable to create render image. Be sure the output render path is correct"
                        )
            return False
コード例 #49
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
コード例 #50
0
ファイル: TextEffect.py プロジェクト: griusfux/conceptrpg2
	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()
コード例 #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