Example #1
0
    def __init__(self,x,y,width,height,border, margin, message):
        context = bpy.context
        
        self.x = x #middle of text box
        self.y = y #top of text box
        self.def_width = width
        self.def_height = height
        self.hang_indent = '-'
        
        self.width = width * get_dpi_factor()
        self.height = height * get_dpi_factor()
        self.border = border * get_dpi_factor()
        self.margin = margin * get_dpi_factor()
        self.spacer = 7 * get_dpi_factor()  # pixels between text lines
        self.is_collapsed = False
        self.is_hovered = False
        self.collapsed_msg = "Click for Help"

        self.text_size = 12
        self.text_dpi = get_dpi()
        blf.size(0, self.text_size, self.text_dpi)
        self.line_height = self.txt_height('A')
        self.raw_text = message
        self.text_lines = []
        self.format_and_wrap_text()
        
        #print('>>> dpi: %f' % self.text_dpi)
        self.window_dims = (context.window.width, context.window.height)
def draw_callback_px(self, context):
    wm = context.window_manager
    sc = context.scene

    if not wm.polycount_run:
        return

    font_size  = sc.polycount_font_size
    pos_x, pos_y = get_display_location(context)

    # draw text in the 3d-view
    # ========================
    blf.size(0, sc.polycount_font_size, 72)
    r, g, b = sc.polycount_font_color
    bgl.glColor3f(r, g, b)

    view3dId = get_space_id(context.space_data)

    visible_tri_count = PolyCountOperator.visible_triangle_count.get(view3dId, -1)

    if visible_tri_count > -1:
        text = "All: " + format(visible_tri_count, 'd') + "triangles"
        text1height = blf.dimensions(0, text)[1]

        blf.position(0, pos_x, pos_y - text1height, 0)
        blf.draw(0, text)

    selection_tri_count = PolyCountOperator.selection_triangle_count.get(view3dId, -1);

    if selection_tri_count > 0:
        text = "Selection: " + format(selection_tri_count, ',d') + " triangles"
        text2height = blf.dimensions(0, text)[1]

        blf.position(0, pos_x, pos_y - text1height - text2height - 5, 0)
        blf.draw(0, text)
Example #3
0
def draw_callback_px(self, context):
    """Draw on the viewports"""
    # BLF drawing routine
    font_id = font_info["font_id"]
    blf.position(font_id, 2, 80, 0)
    blf.size(font_id, 50, 72)
    blf.draw(font_id, "Hello World")
Example #4
0
 def fit_box_width_to_text_lines(self):
     '''
     shrink width of box to fit width of text
     '''
     blf.size(0, self.text_size, self.text_dpi)
     max_width = max(self.txt_width(line) for line in self.text_lines)
     self.width = min(max_width + 2*self.border, self.def_width)
def draw_rectangle_callback_px(not_used):
    import blf

    if len(bpy.data.movieclips) < 1:
        return

    scene = bpy.context.scene
    movieclip = bpy.data.movieclips[0]

    region, width, height = get_clipeditor_region()
    if not region:
        return

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

    # set identity matrices
    view_setup()

    draw_rectangle(region, width, height, 1.0)

    # restore opengl defaults
    view_reset(viewport)
    glColor4f(1.0, 1.0, 1.0, 1.0)


    # draw some text
    font_id = 0

    # draw some text
    blf.position(font_id, 15, 30, 0)
    blf.size(font_id, 20, 72)
    blf.draw(font_id, "Movie Clip: {0}".format(movieclip.name))
Example #6
0
def draw_text(x_pos, y_pos, display_text, rgb, fsize, right=False):
    gap = 12
    font_id = 0
    blf.size(font_id, fsize, 72)
    # height of one line
    mwidth, mheight = blf.dimensions(font_id, "Tp")  # uses high/low letters
    # split lines
    mylines = display_text.split("|")
    idx = len(mylines) - 1
    maxwidth = 0
    maxheight = len(mylines) * mheight
    # -------------------
    # Draw all lines
    # -------------------
    for line in mylines:
        text_width, text_height = blf.dimensions(font_id, line)
        if right is True:
            newx = x_pos - text_width - gap
        else:
            newx = x_pos
        # calculate new Y position
        new_y = y_pos + (mheight * idx)
        # Draw
        blf.position(font_id, newx, new_y, 0)
        bgl.glColor4f(rgb[0], rgb[1], rgb[2], rgb[3])
        blf.draw(font_id, " " + line)
        # sub line
        idx -= 1
        # saves max width
        if maxwidth < text_width:
            maxwidth = text_width

    return maxwidth, maxheight
Example #7
0
File: font.py Project: DCubix/Compz
	def draw(self, text, x, y):
		if self.shadowed:
			blf.enable(self.id, blf.SHADOW)
			blf.shadow_offset(self.id, self.shadow_offset[0],
				self.shadow_offset[1])
			blf.shadow(self.id, 3, 0, 0, 0, 0.8)
		else:
			blf.disable(self.id, blf.SHADOW)

		_, h = self.measure("E]")

		blf.position(self.id, x, -y, 0)
		blf.size(self.id, int(self.size), 72)

		glPushMatrix()
		glLoadIdentity()
		# horrible hack for issue #1
		if Font.first:
			glTranslatef(0, h / 2 + 4, 0)
			Font.first = False
		else:
			glTranslatef(0, h, 0)
		glScalef(1, -1, 1)
		blf.draw(self.id, text)
		glPopMatrix()

		if self.shadowed:
			blf.disable(self.id, blf.SHADOW)
Example #8
0
def draw_callback_px(self, context):
    scene = context.scene

    font_id = 0  # XXX, need to find out how best to get this.

    # draw some text
    blf.position(font_id, 15, 30, 0)
    blf.size(font_id, 18, 72)
    blf.enable(font_id, blf.SHADOW)
    blf.shadow(font_id, 5, 0.0, 0.0, 0.0, 1.0)

    # Shorten / cut off milliseconds
    time_total = str(timedelta(seconds = timer["total"]))
    pos = time_total.rfind(".")
    if pos != -1:
        time_total = time_total[0:pos+3]

    time_estimated = str(timedelta(seconds = (timer["average"] * (scene.frame_end - scene.frame_current))))
    pos = time_estimated.rfind(".")
    if pos != -1:
        time_estimated = time_estimated[0:pos]


    blf.draw(font_id, "Total render time " + time_total)
    if timer["is_rendering"] and scene.frame_current != scene.frame_start:
        blf.position(font_id, 15, 12, 0)
        blf.draw(font_id, "Estimated completion: " + time_estimated)

    # restore defaults
    blf.disable(font_id, blf.SHADOW)
Example #9
0
def draw_pins(self, context):
    x = self.x
    y = self.y
    
    font_id = 0
    
    ignore_click = False
    self.callmenu = None
    for menu in list(PinnedMenus):
        if not PinnedMenus[menu]['set']:
            ignore_click = True
            mxy = get_magnet_xy(x, y)
            PinnedMenus[menu]['x'] = mxy[0]
            PinnedMenus[menu]['y'] = mxy[1]
            if self.RMB:# or self.LMB:
                PinnedMenus[menu]['set'] = True

        hover = draw_button(x, y, PinnedMenus[menu]['x'] - 60, PinnedMenus[menu]['y'], 120, 22)
        blf.size(font_id, 12, 72)
        draw_text(PinnedMenus[menu]['x'] - 54, PinnedMenus[menu]['y'] - 4, PinnedMenus[menu]['name'])
        if not PinnedMenus[menu]['set']:
            blf.size(font_id, 10, 72)
            draw_text(PinnedMenus[menu]['x'] + 28, PinnedMenus[menu]['y'] - 3, '(move)')
        
        if hover and not ignore_click:
            if self.RMB:
                PinnedMenus[menu]['set'] = False
            else:
                self.callmenu = menu
Example #10
0
def draw_text(text, position, align="LEFT"):
    """Draw 12pt white text at position (3D-Vector) aligned to the left"""
    pos = to_screen_coord(position)
    if pos is None:
        # we cannot draw because the point is not on the screen
        return

    # [PART VI]
    # BRIDGEKEEPER: Hee hee heh. Stop! What... is your name?
    # ARTHUR: It is 'Arthur', King of the Britons.
    # BRIDGEKEEPER: What... is your quest?
    # ARTHUR: To draw text on the screen.
    font_id = 0
    size = 12
    color = (1.0, 1.0, 1.0, 1.0)
    bgl.glColor4f(*color)
    blf.size(font_id, size, 72)

    if align == "CENTER":
        # get length of text, place text .5 of length to the left of the coord.
        text_width, text_height = blf.dimensions(font_id, text)
        pos.x -= text_width / 2

    blf.position(font_id, pos.x, pos.y, 0)

    # BRIDGEKEEPER: What... is the OpenGL command for drawing text?
    # ARTHUR: What do you mean? Blender's bfl module can do that for me!
    # BRIDGEKEEPER: Huh? I-- I didn't know that. Auuuuuuuugh!

    blf.draw(font_id, text)
    def draw_callback_px(self, context):
        if context.region.id != self.region_id:
            return
        posx = 70
        posy1 = 30
        posy2 = 50
        text_interval = 5
        font_id = 0
        blf.size(font_id, 11, context.user_preferences.system.dpi)
        bgl.glEnable(bgl.GL_BLEND)
        if self.changing_mgtype:
            bgl.glColor4f(1.0, 1.0, 0.0, 1.0)
        else:
            bgl.glColor4f(1.0, 1.0, 1.0, 1.0)

        # draw origin
        bgl.glLineWidth(2)
        radius = path_threthold
        radius2 = radius + 5
        x, y, z = self.path[0]
        bgl.glBegin(bgl.GL_LINES)
        for i in range(4):
            r = math.pi / 2 * i + math.pi / 4
            bgl.glVertex2f(x + radius * math.cos(r), y + radius * math.sin(r))
            bgl.glVertex2f(x + radius2 * math.cos(r),
                           y + radius2 * math.sin(r))
        bgl.glEnd()
        bgl.glLineWidth(1)

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

        # draw txt
        if self.action or self.mgitem:
            x = posx
            for txt in self.action:
                blf.position(font_id, x, posy1, 0)
                blf.draw(font_id, txt)
                text_width, text_height = blf.dimensions(font_id, txt)
                x += text_width + text_interval
            if self.mgitem:
                blf.position(font_id, posx, posy2, 0)
                blf.draw(font_id, self.mgitem.name)
        else:
            #blf.position(font_id, posx, posy2, 0)
            #blf.draw(font_id, '[Mouse Gesture]')
            pass

        # restore opengl defaults
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        blf.size(0, 11, context.user_preferences.system.dpi)
Example #12
0
	def text( self, text, arg1=0, arg2=0, arg3=0 ):
		x = 0
		y = 0
		z = 0
		rx = 0
		ry = 0
		rz = 0

		if type( arg1 ) is mathutils.Vector():
			x = arg1.x
			y = arg1.y
			z = arg1.z
			if type( arg2 ) is mathutils.Vector():
				rx = arg2.x
				ry = arg2.y
				rz = arg2.z

		elif type( arg1 ) is bge.types.KX_GameObject or type( arg1 ) is str:
			if type( arg1 ) is str:
				arg1 = self.getObjectByName( arg1 )
			if arg1 is not 0:
				o = self.getPosition( arg1 )
				x = o.x
				y = o.y
				z = o.z
				# translation vector
				if type( arg2 ) is mathutils.Vector():
					x += arg2.x
					y += arg2.y
					z += arg2.z
				# rotation vector
				if type( arg3 ) is mathutils.Vector():
					rx = arg3.x
					ry = arg3.y
					rz = arg3.z
		
		elif type( arg1 ) is float and type( arg2 ) is float and type( arg3 ) is float:
			x = arg1
			y = arg2
			z = arg3

		elif type( arg1 ) is int and type( arg2 ) is int and type( arg3 ) is int:
			x = arg1
			y = arg2
			z = arg3
		
		width = bge.render.getWindowWidth()
		height = bge.render.getWindowHeight()
		ratiow = 1./width
		ratioh = 1./height
		bgl.glPushMatrix()
		bgl.glTranslatef( x,y,z )
#TODO transform angles to matrix!
		# bgl.glRotate( rx,ry,rz )
		bgl.glScalef( ratiow, ratioh, 0 )
		blf.position( self.font, 0,0,0 )
		blf.size( self.font, self.tsize, 300 )
		bgl.glColor3f( self.tcolor.x, self.tcolor.y, self.tcolor.z )
		blf.draw( self.font, text )
		bgl.glPopMatrix()
Example #13
0
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'])
def draw_callback(self, context):
    # polling
    if context.mode == "EDIT_MESH":
        return

    """
    # retrieving ID property data
    try:
        texts = context.scene['GamePropsVisualizer']
    except:
        return

    if not texts:
        return
    """

    texts = context.scene["GamePropsVisualizer"]

    # draw
    i = 0

    blf.size(0, 12, 72)

    bgl.glColor3f(1.0, 1.0, 1.0)
    for ob in bpy.context.selected_objects:
        for pi, p in enumerate(ob.game.properties):
            blf.position(0, texts[i], texts[i + 1] - (pi + 1) * 14, 0)
            if p.type == "FLOAT":
                t = p.name + ":  " + str("%g" % p.value)
            else:
                t = p.name + ":  " + str(p.value)
            blf.draw(0, t)
            i += 2
Example #15
0
def general_func_callback(self,context):
    aspect, mid = menu_utils.view3d_get_size_and_mid(context)
        # draw some text
    blf.position(0, mid[0], mid[1]+100, 0)
    blf.size(0, 20, 72)
    blf.draw(0, self.message)
    menu_utils.blf_text_wrap(self.help, self.wrap, 0, 12 , 76, 10, aspect[1]-30)
def draw_callback_px(self, context):
    #print("callback_px")
    # Maybe print a nice red circle in some corner

    bgl.glPushAttrib(bgl.GL_CLIENT_ALL_ATTRIB_BITS)

    FONT_RGBA = (0.8, 0.1, 0.1, 0.5)
    bgl.glColor4f(*FONT_RGBA)

    font_size = 11
    DPI = 72

    blf.size(0, font_size, DPI)
    msg = "Logging..."
    
    msg_w,msg_h = blf.dimensions(0, msg)

    pos_x = context.region.width - msg_w
    pos_y = font_size / 2
    blf.position(0, pos_x, pos_y, 0)
    #blf.position(0, 10, 10, 0)

    blf.draw(0, msg)

    bgl.glPopAttrib()

    pass
def draw_callback_px(self, context):

    for n, area in enumerate(self.areas):
        if context.area.x == area.x and context.area.y == area.y:  #then this is where our mouse is
            
            font_id = 0  # XXX, need to find out how best to get this.
            height = context.region.height
            width = context.region.width
            dims = blf.dimensions(0, self.messages[n])
            #blf.position(font_id, 10, height - 10 - dims[1], 0)  #top left
            blf.position(font_id, width - 10 - 2* dims[0], 10 + dims[1]/2, 0)
            
            blf.size(font_id, 20, 72)
            blf.draw(font_id, self.messages[n])
        
            if (self.mouse_raw[0] > area.x and self.mouse_raw[0] < area.x + area.width) and \
                (self.mouse_raw[1] > area.y and self.mouse_raw[1] < area.y + area.height):
                #label the mouse
                dims = blf.dimensions(0,'MOUSE %i' %n)
                x = self.mouse_region_coord[0] - .5 * dims[0]
                y = self.mouse_region_coord[1] + dims[1]
                blf.position(font_id,x,y,0)
                blf.draw(font_id,'MOUSE %i' % n)
        
    
            if len(self.area_data[n]):
                N = len(self.areas)
                color = (n/N, .5*n/N, (1-n/N), 1)
                draw_3d_points_specific_region(context.region, context.space_data.region_3d, self.area_data[n], color, 3)
Example #18
0
def draw_callback(self, context):
    mid = int(360 * self.recv / self.fsize)
    cx = 200
    cy = 30
    blf.position(0, 230, 23, 0)
    blf.size(0, 20, 72)
    blf.draw(0, "{0:2d}% of {1}".format(100 * self.recv // self.fsize, self.hfsize))

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.7, 0.7, 0.7, 0.8)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2i(cx, cy)
    for i in range(mid):
        x = cx + 20 * math.sin(math.radians(float(i)))
        y = cy + 20 * math.cos(math.radians(float(i)))
        bgl.glVertex2f(x, y)
    bgl.glEnd()

    bgl.glColor4f(0.0, 0.0, 0.0, 0.6)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2i(cx, cy)
    for i in range(mid, 360):
        x = cx + 20 * math.sin(math.radians(float(i)))
        y = cy + 20 * math.cos(math.radians(float(i)))
        bgl.glVertex2f(x, y)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Example #19
0
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))
Example #20
0
 def __render_text(size, x, y, s):
     # フォントサイズを指定
     blf.size(0, size, 72)
     # 描画位置を指定
     blf.position(0, x, y, 0)
     # テキストを描画
     blf.draw(0, s)
	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")
Example #22
0
def draw_callback_px(self, context):
    from bgl import glColor3f
    font_id = 0  # XXX, need to find out how best to get this.
    blf.size(font_id, 12, 72)

    data_matrix, data_quat, data_euler, data_vector, data_vector_array = utils.console_math_data()

    if not data_matrix and not data_quat and not data_euler and not data_vector and not data_vector_array:

        # draw some text
        glColor3f(1.0, 0.0, 0.0)
        blf.position(font_id, 180, 10, 0)
        blf.draw(font_id, "Python Console has no mathutils definitions")
        return

    glColor3f(1.0, 1.0, 1.0)

    region = context.region
    region3d = context.space_data.region_3d

    region_mid_width = region.width / 2.0
    region_mid_height = region.height / 2.0

    # vars for projection
    perspective_matrix = region3d.perspective_matrix.copy()

    def draw_text(text, vec):
        vec_4d = vec.to_4d()
        vec_4d *= perspective_matrix
        if vec_4d.w > 0.0:
            x = region_mid_width + region_mid_width * (vec_4d.x / vec_4d.w)
            y = region_mid_height + region_mid_height * (vec_4d.y / vec_4d.w)

            blf.position(font_id, x + 3.0, y - 4.0, 0.0)
            blf.draw(font_id, text)

    # points
    if data_vector:
        for key, vec in data_vector.items():
            draw_text(key, vec)

    # lines
    if data_vector_array:
        for key, vec in data_vector_array.items():
            draw_text(key, vec[0])

    # matrix
    if data_matrix:
        for key, mat in data_matrix.items():
            draw_text(key, mat[3])

    if data_quat:
        loc = context.scene.cursor_location.copy()
        for key, mat in data_quat.items():
            draw_text(key, loc)

    if data_euler:
        loc = context.scene.cursor_location.copy()
        for key, mat in data_euler.items():
            draw_text(key, loc)
def draw_callback_px(n_id, data):

    space = bpy.context.space_data
  
    ng_view = space.edit_tree
    # ng_view can be None
    if not ng_view:
        return
    ng_name = space.edit_tree.name
    if not (data['tree_name'] == ng_name):
        return
    if not isinstance(ng_view, node_tree.SverchCustomTree):
        return

    lines = data.get('content', 'no data')
    x, y = data.get('location', (120, 120))
    color = data.get('color', (0.1, 0.1, 0.1))
    font_id = 0
    text_height = 13

    # why does the text look so jagged?
    blf.size(font_id, text_height, 72)  # should check prefs.dpi
    bgl.glColor3f(*color)
    # x = 30  # region.width
    # y = region.height - 40
    ypos = y

    for line in lines:
        blf.position(0, x, ypos, 0)
        blf.draw(0, line)
        ypos -= (text_height * 1.3)
Example #24
0
def drawText2D(color, text):
    font_id = 0  # XXX, need to find out how best to get this.
    # draw some text
    bgl.glColor4f(*color)
    blf.position(font_id, 20, 70, 0)
    blf.size(font_id, 20, 72)
    blf.draw(font_id, text)
Example #25
0
    def draw_callback(self, context):

        if context.region.as_pointer() != self.region:
            return
        glsettings = vagl.GLSettings(context)

        glsettings.push()

        cursor_2d = project(context.region, context.region_data,
                            self.get_cursor_location(context))

        unit_settings = context.scene.unit_settings
        text_lines = []
        for i in range(3):
            if unit_settings.system == 'NONE':
                text = '{:.5f}'.format(self.cursor_location[i])
            else:
                text = bpy.utils.units.to_string(
                    unit_settings.system,
                    'LENGTH',
                    self.cursor_location[i],
                    5,
                    split_unit=unit_settings.use_separate
                )
            text_lines.append(text)

        col = context.user_preferences.themes['Default'].view_3d.space.text_hi
        bgl.glColor3f(*col)
        blf.size(0, 12, context.user_preferences.system.dpi)
        tw_max = max(blf.dimensions(0, t)[0] for t in text_lines)
        if 0:
            p = [cursor_2d[0] - tw_max - 5, cursor_2d[1] - 40, 0]
        else:
            p = [self.mco[0] - tw_max - 5, self.mco[1] - 40, 0]
        th = blf.dimensions(0, '-.0123456789')[1]
        lf = th * 1.2
        for i, text in enumerate(text_lines):
            tw, _ = blf.dimensions(0, text)
            blf.position(0, p[0] + tw_max - tw, p[1], p[2])
            vagl.blf_draw(0, text)
            p[1] -= lf

        if 0:
            p = [cursor_2d[0] + 5, cursor_2d[1] - 40, 0]
        else:
            p = [self.mco[0] + 5, self.mco[1] - 40, 0]
        if self.use_snap:
            blf.position(0, *p)
            vagl.blf_draw(0, 'Snap')
        p[1] -= lf
        if self.use_precision:
            blf.position(0, *p)
            vagl.blf_draw(0, 'Precision')
        p[1] -= lf
        if self.use_depth:
            blf.position(0, *p)
            vagl.blf_draw(0, 'Depth')
        p[1] -= lf

        glsettings.pop()
Example #26
0
def draw_callback_px(self, context):
    
    font_id = 0  # XXX, need to find out how best to get this.

    # draw some text
    y = context.region.height
    dims = blf.dimensions(0, 'A')
    
    blf.position(font_id, 10, y - 20 - dims[1], 0)
    blf.size(font_id, 20, 72)  
        
    if context.area.x == self.area_align.x:
        blf.draw(font_id, "Align: "+ self.align_msg)
        points = [self.obj_align.matrix_world * p for p in self.align_points]
        color = (1,0,0,1)
    else:
        blf.draw(font_id, "Base: " + self.base_msg)
        points = [self.obj_align.matrix_world * p for p in self.base_points]
        color = (0,1,0,1)
    
    draw_3d_points_revised(context, points, color, 4)
    
    for i, vec in enumerate(points):
        ind = str(i)
        draw_3d_text(context, font_id, ind, vec)
Example #27
0
def draw_callback(self, context):

    scene = context.scene
    x = int(round(context.region.width * 0.01 + (self._t_target - scene.frame_start) * self._ppf))
    string = str(self._t_target)
    string = string[0 : string.index(".") + 3]
    font_id = 0  # XXX, need to find out how best to get this.

    # draw marker
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1, 0, 0, 1)
    bgl.glLineWidth(2)

    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2i(x, 17)
    bgl.glVertex2i(x, context.region.height)
    bgl.glEnd()

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    # draw frame number
    if self._show_frame_indicator:
        blf.position(font_id, x + 5, 21, 0)
        blf.size(font_id, 12, 72)
        blf.draw(font_id, string)
Example #28
0
def draw_text(text, x, y, size, color=(1, 1, 1, 0.5)):
    font_id = 0
    # bgl.glColor4f(*color)
    blf.color(font_id, color[0], color[1], color[2], color[3])
    blf.position(font_id, x, y, 0)
    blf.size(font_id, size, 72)
    blf.draw(font_id, text)
Example #29
0
def draw_callback_px(self, context):
    print("mouse points", len(self.mouse_path))

    font_id = 0  # XXX, need to find out how best to get this.

    # draw some text
    blf.position(font_id, 15, 30, 0)
    blf.size(font_id, 20, 72)
    blf.draw(font_id, "Hello Word " + str(len(self.mouse_path)))

    # 50% alpha, 2 pixel width line
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
    bgl.glLineWidth(2)

    bgl.glBegin(bgl.GL_LINE_STRIP)
    for x, y in self.mouse_path:
        bgl.glVertex2i(x, y)

    bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
def draw_callback(self, context):
    # polling
    if context.mode == 'EDIT_MESH':
        return
    # retrieving ID property data
    try:
        #print(context.scene['GamePropsVisualiser'])
        texts = context.scene['GamePropsVisualiser']
        
    except:
        return
    if not texts:
        return
    
    # draw
    i=0

    blf.size(0, 12, 72)
   
        
    bgl.glColor3f(1.0,1.0,1.0)
    for ob in bpy.context.selected_objects:
        for pi,p in enumerate(ob.game.properties):
            blf.position(0, texts[i], texts[i+1]-(pi+1)*14, 0)
            if p.type=='FLOAT':
                t=p.name+':  '+ str('%g'% p.value)
            else:    
                t=p.name+':  '+ str(p.value)
            blf.draw(0, t)
            i+=2
Example #31
0
    def draw_callback(cls, context):
        prefs = compat.get_user_preferences(context).addons[__package__].preferences

        if context.window.as_pointer() != cls.origin["window"]:
            return      # Not match target window.

        rect = cls.calc_draw_area_rect(context)
        if not rect:
            return      # No draw target.

        draw_area_min_x, draw_area_min_y, draw_area_max_x, draw_area_max_y = rect
        _, _, _, origin_x, origin_y = cls.get_origin(context)
        width = draw_area_max_x - origin_x
        height = draw_area_max_y - origin_y
        if width == height == 0:
            return

        region = context.region
        area = context.area
        if region.type == 'WINDOW':
            region_min_x, region_min_y, region_max_x, region_max_y = get_window_region_rect(area)
        else:
            region_min_x = region.x
            region_min_y = region.y
            region_max_x = region.x + region.width - 1
            region_max_y = region.y + region.height - 1
        if not intersect_aabb(
                [region_min_x, region_min_y], [region_max_x, region_max_y],
                [draw_area_min_x + 1, draw_area_min_y + 1], [draw_area_max_x - 1, draw_area_max_x - 1]):
            # We don't need to draw if draw area is not overlapped with region.
            return

        current_time = time.time()
        region_drawn = False

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

        scissor_box = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
        # Clip 'TOOLS' and 'UI' region from 'WINDOW' region if need.
        # This prevents from drawing multiple time when
        # user_preferences.system.use_region_overlap is True.
        if context.area.type == 'VIEW_3D' and region.type == 'WINDOW':
            x_min, y_min, x_max, y_max = get_region_rect_on_v3d(context)
            bgl.glScissor(x_min, y_min, x_max - x_min + 1, y_max - y_min + 1)

        # Get string height in draw area.
        sh = blf.dimensions(0, string.printable)[1]
        x = origin_x - region.x
        y = origin_y - region.y

        # Draw last operator.
        operator_history = cls.removed_old_operator_history()
        if prefs.show_last_operator and operator_history:
            time_, bl_label, idname_py, _ = operator_history[-1]
            if current_time - time_ <= prefs.display_time:
                compat.set_blf_font_color(font_id, *prefs.color, 1.0)

                # Draw operator text.
                text = bpy.app.translations.pgettext_iface(bl_label, "Operator")
                text += " ('{}')".format(idname_py)
                offset_x = cls.get_text_offset_for_alignment(font_id, text, context)
                blf.position(font_id, x + offset_x, y, 0)
                if prefs.background:
                    draw_text_background(text, font_id, x + offset_x, y, prefs.color_background)
                draw_text(text, font_id, prefs.color, prefs.shadow, prefs.color_shadow)
                y += sh + sh * cls.HEIGHT_RATIO_FOR_SEPARATOR * 0.2

                # Draw separator.
                sw = blf.dimensions(font_id, "Left Mouse")[0]
                offset_x = cls.get_offset_for_alignment(sw, context)
                draw_line([x + offset_x, y], [x + sw + offset_x, y], prefs.color, prefs.shadow, prefs.color_shadow)
                y += sh * cls.HEIGHT_RATIO_FOR_SEPARATOR * 0.8

                region_drawn = True

            else:
                y += sh + sh * cls.HEIGHT_RATIO_FOR_SEPARATOR

        # Draw hold modifier keys.
        drawing = False     # TODO: Need to check if drawing is now on progress.
        compat.set_blf_font_color(font_id, *prefs.color, 1.0)
        margin = sh * 0.2
        if cls.hold_modifier_keys or drawing:
            mod_keys = cls.sorted_modifier_keys(cls.hold_modifier_keys)
            if drawing:
                text = ""
            else:
                text = " + ".join(mod_keys)

            offset_x = cls.get_text_offset_for_alignment(font_id, text, context)

            # Draw rounded box.
            box_height = sh + margin * 2
            box_width = blf.dimensions(font_id, text)[0] + margin * 2
            draw_rounded_box(x - margin + offset_x, y - margin,
                             box_width, box_height, box_height * 0.2,
                             prefs.background, prefs.color_background)

            # Draw key text.
            blf.position(font_id, x + offset_x, y + margin, 0)
            draw_text(text, font_id, prefs.color, prefs.shadow, prefs.color_shadow)
            bgl.glColor4f(*prefs.color, 1.0)

            region_drawn = True

        y += sh + margin * 2

        # Draw event history.
        event_history = cls.removed_old_event_history()
        y += sh * cls.HEIGHT_RATIO_FOR_SEPARATOR
        for _, event_type, modifiers, repeat_count in event_history[::-1]:
            color = prefs.color
            compat.set_blf_font_color(font_id, *color, 1.0)

            text = get_display_event_text(event_type.name)
            if modifiers:
                mod_keys = cls.sorted_modifier_keys(modifiers)
                text = "{} + {}".format(" + ".join(mod_keys), text)
            if repeat_count > 1:
                text += " x{}".format(repeat_count)

            offset_x = cls.get_text_offset_for_alignment(font_id, text, context)
            blf.position(font_id, x + offset_x, y, 0)
            if prefs.background:
                draw_text_background(text, font_id, x + offset_x, y, prefs.color_background)
            draw_text(text, font_id, prefs.color, prefs.shadow, prefs.color_shadow)

            y += sh

            region_drawn = True

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glScissor(*scissor_box)
        bgl.glLineWidth(1.0)

        if region_drawn:
            cls.draw_regions_prev.add(region.as_pointer())
Example #32
0
    def calc_draw_area_size(cls, context):
        """Return draw area size.

        Draw format:

            Overview:
                ....
                Event history[-3]
                Event history[-2]
                Event history[-1]

                Hold modifier key list
                ----------------
                Operator history

            Event history format:
                With count: {key} x{count}
                With modifier key: {modifier key} + {key}

            Hold modifier key list format:
                 --------------     --------------
                |{modifier key}| + |{modifier key}|
                 --------------     --------------
        """

        prefs = compat.get_user_preferences(context).addons[__package__].preferences

        font_size = prefs.font_size
        font_id = 0         # TODO: font_id should be constant.
        dpi = compat.get_user_preferences(context).system.dpi
        blf.size(font_id, font_size, dpi)

        # Get string height in draw area.
        sh = blf.dimensions(font_id, string.printable)[1]

        # Calculate width/height of draw area.
        draw_area_width = 0
        draw_area_height = 0

        if prefs.show_last_operator:
            operator_history = cls.removed_old_operator_history()
            if operator_history:
                _, name, idname_py, _ = operator_history[-1]
                text = bpy.app.translations.pgettext(name, "Operator")
                text += " ('{}')".format(idname_py)

                sw = blf.dimensions(font_id, text)[0]
                draw_area_width = max(draw_area_width, sw)
            draw_area_height += sh + sh * cls.HEIGHT_RATIO_FOR_SEPARATOR

        if cls.hold_modifier_keys:
            mod_names = cls.sorted_modifier_keys(cls.hold_modifier_keys)
            text = " + ".join(mod_names)

            sw = blf.dimensions(font_id, text)[0]
            draw_area_width = max(draw_area_width, sw)

        draw_area_height += sh

        event_history = cls.removed_old_event_history()

        if cls.hold_modifier_keys or event_history:
            sw = blf.dimensions(font_id, "Left Mouse")[0]
            draw_area_width = max(draw_area_width, sw)
            draw_area_height += sh * cls.HEIGHT_RATIO_FOR_SEPARATOR

        for _, event_type, modifiers, repeat_count in event_history[::-1]:
            text = event_type.names[event_type.name]
            if modifiers:
                mod_keys = cls.sorted_modifier_keys(modifiers)
                text = "{} + {}".format(" + ".join(mod_keys), text)
            if repeat_count > 1:
                text += " x{}".format(repeat_count)

            sw = blf.dimensions(font_id, text)[0]
            draw_area_width = max(draw_area_width, sw)
            draw_area_height += sh

        draw_area_height += sh

        # Add margin.
        draw_area_height += 30
        draw_area_width += 30

        return draw_area_width, draw_area_height
Example #33
0
def DRAW_Overlay(self, context):

    np_print('DRAW_Overlay_START',';','NP020PL.flag = ', NP020PL.flag)

    flag = NP020PL.flag
    helper = NP020PL.helper
    region = bpy.context.region
    rv3d = bpy.context.region_data
    rw = region.width
    rh = region.height
    co2d = view3d_utils.location_3d_to_region_2d(region, rv3d, helper.location)
    frompoints = NP020PL.frompoints
    topoints = NP020PL.topoints


    col_line_main = (1.0, 1.0, 1.0, 1.0)
    col_line_shadow = (0.1, 0.1, 0.1, 0.25)

    #greys:
    mark_col_A = (0.25, 0.25, 0.25, 1.0)
    mark_col_B = (0.5, 0.5, 0.5, 1.0)
    mark_col_C = (0.75, 0.75, 0.75, 1.0)

    #marins
    mark_col_A = (0.25, 0.35, 0.4, 1.0)
    mark_col_B = (0.5, 0.6, 0.65, 1.0)
    mark_col_C = (0.67, 0.77, 0.82, 1.0)

    # writing the dots for recwidget widget at center of scene:

    r = 12
    angstep = 20
    psize = 25
    pofsetx = 15
    pofsety = 15
    fsize = 20
    fofsetx = -8
    fofsety = -7



    widget_circle = construct_circle_2d(r, angstep)


    if flag == 'RUNTRANSF0':
        instruct = 'place start for point a'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap'
        keys_neg = 'RMB, ESC - quit'
        frompoints[0] = helper.location

    elif flag == 'RUNTRANST0':
        instruct = 'place target for point a'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value'
        keys_neg = 'RMB, ESC - quit'
        topoints[0] = helper.location

    elif flag == 'RUNTRANSF1':
        instruct = 'place start for point b'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align A (translate)'
        keys_neg = 'ESC - quit'
        frompoints[1] = helper.location

    elif flag == 'RUNTRANST1':
        instruct = 'place target for point b'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align A (translate)'
        keys_neg = 'ESC - quit'
        topoints[1] = helper.location

    elif flag == 'RUNTRANSF2':
        instruct = 'place start for point c'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align AB (translate, rotate)'
        keys_neg = 'ESC - quit'
        frompoints[2] = helper.location

    elif flag == 'RUNTRANST2':
        instruct = 'place target for point c'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align AB (translate, rotate)'
        keys_neg = 'ESC - quit'
        topoints[2] = helper.location


    # ON-SCREEN INSTRUCTIONS:


    keys_nav = ''

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)


    # LINE:

    for i, frompoint in enumerate(frompoints):
        topoint = topoints[i]
        if frompoint != None and topoint != None:
            bgl.glColor4f(*col_line_shadow)
            bgl.glLineWidth(1.4)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            frompoint = view3d_utils.location_3d_to_region_2d(region, rv3d, frompoint)
            topoint = view3d_utils.location_3d_to_region_2d(region, rv3d, topoint)
            bgl.glVertex2f((frompoint[0] - 1), (frompoint[1] - 1))
            bgl.glVertex2f((topoint[0] - 1), (topoint[1] - 1))
            bgl.glEnd()

            bgl.glColor4f(*col_line_main)
            bgl.glLineWidth(1.4)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            bgl.glVertex2f(*frompoint)
            bgl.glVertex2f(*topoint)
            bgl.glEnd()


    # drawing of markers:
    i = 0
    for point in frompoints:
        if point != None:
            point = view3d_utils.location_3d_to_region_2d(region, rv3d, point)
            point[0] = point[0] + pofsetx
            point[1] = point[1] + pofsety
            widget = []
            for co in widget_circle:
                c = [0.0, 0.0]
                c[0] = co[0] + point[0] + pofsetx
                c[1] = co[1] + point[1] + pofsety
                widget.append(c)
            bgl.glEnable(bgl.GL_BLEND)
            if i == 0:
                bgl.glColor4f(*mark_col_A)
                mark = "A"
            elif i == 1:
                bgl.glColor4f(*mark_col_B)
                mark = "B"
            elif i == 2:
                bgl.glColor4f(*mark_col_C)
                mark = "C"

            '''
            bgl.glLineWidth(1)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glVertex2f(*widget[len(widget) - 1])
            bgl.glEnd()
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glEnd()
            '''
            font_id = 0
            bgl.glEnable(bgl.GL_POINT_SMOOTH)
            bgl.glPointSize(psize)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2f(*point)
            bgl.glEnd()
            bgl.glDisable(bgl.GL_POINT_SMOOTH)

            bgl.glColor4f(1.0, 1.0, 1.0, 0.75)
            blf.size(font_id, fsize, 72)
            blf.position(font_id, point[0] + fofsetx, point[1] + fofsety, 0)
            blf.draw(font_id, mark)
            i = i + 1

    i = 0
    for point in topoints:
        if point != None:
            point = view3d_utils.location_3d_to_region_2d(region, rv3d, point)
            point[0] = point[0] + pofsetx
            point[1] = point[1] + pofsety
            widget = []
            for co in widget_circle:
                c = [0.0, 0.0]
                c[0] = co[0] + point[0] + pofsetx
                c[1] = co[1] + point[1] + pofsety
                widget.append(c)
            bgl.glEnable(bgl.GL_BLEND)
            if i == 0:
                bgl.glColor4f(*mark_col_A)
                mark = "A'"
            elif i == 1:
                bgl.glColor4f(*mark_col_B)
                mark = "B'"
            elif i == 2:
                bgl.glColor4f(*mark_col_C)
                mark = "C'"
            '''
            bgl.glLineWidth(1)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glVertex2f(*widget[len(widget) - 1])
            bgl.glEnd()
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glEnd()
            '''
            font_id = 0
            bgl.glEnable(bgl.GL_POINT_SMOOTH)
            bgl.glPointSize(psize)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2f(*point)
            bgl.glEnd()
            bgl.glDisable(bgl.GL_POINT_SMOOTH)

            bgl.glColor4f(1.0, 1.0, 1.0, 0.75)
            blf.size(font_id, fsize, 72)
            blf.position(font_id, point[0] + fofsetx, point[1] + fofsety, 0)
            blf.draw(font_id, mark)
            i = i + 1


    #ENDING:

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Example #34
0
def draw_callback_pb(self, context):

    font_id = 0  # XXX, need to find out how best to get this.
    #set_drawing_dpi(display.get_dpi() * scale_factor)
    #dpi_factor = display.get_dpi_factor() * scale_factor
    #line_height = 18 * dpi_factor

    is_bool = False
    is_bevel = False
    is_bevel_3 = False
    is_bevel_2 = False
    is_solidify = False
    is_multiselected = False
    is_notselected = False
    is_noactiveobject = False
    multislist = bpy.context.selected_objects
    activeobject = bpy.context.scene.objects.active
    is_formerge = False
    current_dir = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
    user_preferences = bpy.context.user_preferences
    addon_pref = user_preferences.addons[current_dir].preferences
    x = get_dpi()
    scale_factor = 0.9
    dpi_factor = get_dpi_factor() * scale_factor

    if len(multislist) > 1:
        is_multiselected = True
    if len(multislist) < 1:
        is_notselected = True
    if activeobject == None:
        is_noactiveobject = True

    for obj in bpy.context.selected_objects:
        if obj.name.startswith("AP"):
            is_formerge = True
            pass

    for mode in bpy.context.object.modifiers:
        if mode.type == 'BEVEL':
            if mode.limit_method == 'WEIGHT':
                is_bevel = True
        if mode.type == "BEVEL":
            if mode.profile > 0.70 and mode.profile < 0.72:
                is_bevel_3 = True
                #print("Bevel 3 is true")
        if mode.type == "BEVEL":
            if mode.limit_method == 'ANGLE' or mode.limit_method == 'NONE':
                is_bevel_2 = True
                #print("Bevel 2 is true")
        if mode.type == 'BOOLEAN':
            is_bool = True
        if mode.type == 'SOLIDIFY':
            is_solidify = True
    #Min and Max Idea
    if self.lvl == 1:
        #Show Segments Size
        bgl.glEnable(bgl.GL_BLEND)
        blf.position(font_id, self.click_pos[0],
                     self.click_pos[1] + 0.83 * get_dpi(), 0)
        bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
        blf.size(font_id, 12, get_dpi())
        blf.draw(font_id, "          (Min)")

    if self.lvl == 16:
        #Show Segments Size
        bgl.glEnable(bgl.GL_BLEND)
        blf.position(font_id, self.click_pos[0],
                     self.click_pos[1] + 0.83 * get_dpi(), 0)
        bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
        blf.size(font_id, 12, get_dpi())
        blf.draw(font_id, "                  (Max)")

    #Show Segments Size
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] + 0.55 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 36, get_dpi())
    blf.draw(font_id, str(self.lvl))

    # And Underline Up Top
    #blf.position(font_id, self.click_pos[0], self.click_pos[1]+34, 0)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    bgl.glLineWidth(int(0.032 * get_dpi()))
    bgl.glBegin(bgl.GL_LINE_STRIP)
    #bgl.glVertex2d(20, 40)
    for n in range(-1, int(2.7 * get_dpi())):
        bgl.glVertex2i(self.click_pos[0] + n + 2,
                       self.click_pos[1] + int(get_dpi() / 2.2))
    bgl.glEnd()

    #Show All Bevel Information
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] + 0.208 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(
        font_id, "B-Width - " + '%.3f' % (self.mouse_pos) + " / " + " / " +
        "(W) - " + bpy.context.object.modifiers["Bevel"].offset_type)
    #blf.draw(font_id, "Bevel Width - "  + '%.3f'%( self.mouse_pos) + " / " + "Segments - " + str(self.lvl) + " / " + "(W)idth Method - " + bpy.context.object.modifiers["Bevel"].offset_type)

    # And Underline Up Bottom

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    bgl.glLineWidth(int(0.032 * get_dpi()))
    bgl.glBegin(bgl.GL_LINE_STRIP)

    for n in range(-1, int(2.7 * get_dpi())):
        bgl.glVertex2i(self.click_pos[0] + n + 2,
                       self.click_pos[1] + int(get_dpi() / 10.2))
    bgl.glEnd()

    #Show Additional Mesh Information
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] - 0.13 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    if is_bevel_2 == True:
        blf.draw(font_id, "Standard Mesh")
    elif is_bevel_3 == True:
        blf.draw(
            font_id,
            "CStep / Sstep - Warning: Bevels could not be showing due to bevel baking."
        )
    elif is_bevel == True:
        blf.draw(font_id, "CSsharp / Ssharp")
    elif is_bool == True:
        blf.draw(
            font_id,
            "Pending Boolean - Warning: Bevels could not be showing due to boolean pending."
        )

    if addon_pref.Diagnostics_Mode:
        #Diagnostic
        bgl.glEnable(bgl.GL_BLEND)
        blf.position(font_id, self.click_pos[0],
                     self.click_pos[1] - 0.37 * get_dpi, 0)
        bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
        blf.size(font_id, 12, get_dpi())
        blf.draw(
            font_id,
            "Standard is - " + str(is_bevel_2) + "      " + "Sstep is - " +
            str(is_bevel_3) + "      " + "CSharp is - " + str(is_bevel))
Example #35
0
def draw_callback_px(self, context):

    if context.mode == "EDIT_MESH":
        en0 = context.scene.dt_custom_props.en0

        font_id = 0
        font_size = context.scene.dt_custom_props.fs

        ob_act = context.active_object
        bme = bmesh.from_edit_mesh(ob_act.data)
        mtrx = ob_act.matrix_world

        list_0 = [v.index for v in bme.verts if v.select]
        if len(list_0) != 0:
            p = bme.verts[list_0[0]].co.copy()
            p_loc_2d = location_3d_to_region_2d(context.region,
                                                context.space_data.region_3d,
                                                p)

            q = mtrx * bme.verts[list_0[0]].co.copy()
            q_loc_2d = location_3d_to_region_2d(context.region,
                                                context.space_data.region_3d,
                                                q)

            # -- -- -- -- distance to adjacent vertices
            if context.scene.dt_custom_props.b0 == True:
                list_ = [[v.index for v in e.verts]
                         for e in bme.verts[list_0[0]].link_edges]
                for ek in list_:
                    vi = [i for i in ek if i != list_0[0]][0]
                    p1 = bme.verts[vi].co.copy()
                    loc_0_3d = mtrx * ((p + p1) * 0.5)
                    loc_0_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, loc_0_3d)
                    bgl.glColor4f(1.0, 1.0, 0.0,
                                  context.scene.dt_custom_props.a)
                    blf.position(font_id, loc_0_2d[0] + 4, loc_0_2d[1] + 4, 0)
                    blf.size(font_id, font_size,
                             context.user_preferences.system.dpi)
                    blf.draw(font_id, str(round((p - p1).length, 4)))

            bgl.glLineStipple(4, 0xAAAA)
            bgl.glEnable(bgl.GL_LINE_STIPPLE)

            # -- -- -- -- distance to axis local global
            if context.scene.dt_custom_props.b1 == True:

                # -- -- -- -- local
                if en0 == 'opt0':

                    # -- -- -- -- x axis
                    px = mtrx * Vector((0.0, p[1], p[2]))
                    px_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, px)

                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glColor4f(1.0, 0.0, 0.0,
                                  context.scene.dt_custom_props.a)
                    bgl.glBegin(bgl.GL_LINES)
                    bgl.glVertex2f(q_loc_2d[0], q_loc_2d[1])
                    bgl.glVertex2f(px_loc_2d[0], px_loc_2d[1])
                    bgl.glEnd()
                    bgl.glDisable(bgl.GL_BLEND)

                    if context.scene.dt_custom_props.b2 == False:
                        lx = (q_loc_2d + px_loc_2d) * 0.5
                        bgl.glColor4f(1.0, 0.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, lx[0] + 4, lx[1] + 4, 0)
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)
                        blf.draw(font_id, str(round(p[0], 4)))

                    # -- -- -- -- y axis
                    py = mtrx * Vector((p[0], 0.0, p[2]))
                    py_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, py)

                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glColor4f(0.0, 1.0, 0.0,
                                  context.scene.dt_custom_props.a)
                    bgl.glBegin(bgl.GL_LINES)
                    bgl.glVertex2f(q_loc_2d[0], q_loc_2d[1])
                    bgl.glVertex2f(py_loc_2d[0], py_loc_2d[1])
                    bgl.glEnd()
                    bgl.glDisable(bgl.GL_BLEND)

                    if context.scene.dt_custom_props.b2 == False:
                        ly = (q_loc_2d + py_loc_2d) * 0.5
                        bgl.glColor4f(0.0, 1.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, ly[0] + 4, ly[1] + 4, 0)
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)
                        blf.draw(font_id, str(round(p[1], 4)))

                    # -- -- -- -- z axis
                    pz = mtrx * Vector((p[0], p[1], 0.0))
                    pz_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, pz)

                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glColor4f(0.0, 0.0, 1.0,
                                  context.scene.dt_custom_props.a)
                    bgl.glBegin(bgl.GL_LINES)
                    bgl.glVertex2f(q_loc_2d[0], q_loc_2d[1])
                    bgl.glVertex2f(pz_loc_2d[0], pz_loc_2d[1])
                    bgl.glEnd()
                    bgl.glDisable(bgl.GL_BLEND)

                    if context.scene.dt_custom_props.b2 == False:
                        lz = (q_loc_2d + pz_loc_2d) * 0.5
                        bgl.glColor4f(0.0, 0.0, 1.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, lz[0] + 4, lz[1] + 4, 0)
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)
                        blf.draw(font_id, str(round(p[2], 4)))

                    # -- -- -- --
                    if context.scene.dt_custom_props.b2 == True and context.scene.dt_custom_props.b1 == True:
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)

                        bgl.glColor4f(1.0, 0.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(
                            font_id, q_loc_2d[0] + 4,
                            q_loc_2d[1] + 4 + font_size + 4 + font_size + 4, 0)
                        blf.draw(font_id, 'x ' + str(round(p[0], 4)))

                        bgl.glColor4f(0.0, 1.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, q_loc_2d[0] + 4,
                                     q_loc_2d[1] + 4 + font_size + 4, 0)
                        blf.draw(font_id, 'y ' + str(round(p[1], 4)))

                        bgl.glColor4f(0.0, 0.0, 1.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, q_loc_2d[0] + 4, q_loc_2d[1] + 4,
                                     0)
                        blf.draw(font_id, 'z ' + str(round(p[2], 4)))

                # -- -- -- -- global
                elif en0 == 'opt1':

                    # -- -- -- -- x axis
                    ip_x = intersect_line_plane(
                        q, q + (Vector((1.0, 0.0, 0.0)) * 0.1),
                        Vector((0.0, 1.0, 0.0)), Vector((1.0, 0.0, 0.0)))
                    ip_x_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, ip_x)

                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glColor4f(1.0, 0.0, 0.0,
                                  context.scene.dt_custom_props.a)
                    bgl.glBegin(bgl.GL_LINES)
                    bgl.glVertex2f(q_loc_2d[0], q_loc_2d[1])
                    bgl.glVertex2f(ip_x_loc_2d[0], ip_x_loc_2d[1])
                    bgl.glEnd()
                    bgl.glDisable(bgl.GL_BLEND)

                    if context.scene.dt_custom_props.b2 == False:
                        loc_1_2d = (q_loc_2d + ip_x_loc_2d) * 0.5
                        bgl.glColor4f(1.0, 0.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, loc_1_2d[0] + 4, loc_1_2d[1] + 4,
                                     0)
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)
                        blf.draw(font_id, str(round((q - ip_x).length, 4)))

                    # -- -- -- -- y axis
                    ip_y = intersect_line_plane(
                        q, q + (Vector((0.0, 1.0, 0.0)) * 0.1),
                        Vector((1.0, 0.0, 0.0)), Vector((0.0, 1.0, 0.0)))
                    ip_y_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, ip_y)

                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glColor4f(0.0, 1.0, 0.0,
                                  context.scene.dt_custom_props.a)
                    bgl.glBegin(bgl.GL_LINES)
                    bgl.glVertex2f(q_loc_2d[0], q_loc_2d[1])
                    bgl.glVertex2f(ip_y_loc_2d[0], ip_y_loc_2d[1])
                    bgl.glEnd()
                    bgl.glDisable(bgl.GL_BLEND)

                    if context.scene.dt_custom_props.b2 == False:
                        loc_2_2d = (q_loc_2d + ip_y_loc_2d) * 0.5
                        bgl.glColor4f(0.0, 1.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, loc_2_2d[0] + 4, loc_2_2d[1] + 4,
                                     0)
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)
                        blf.draw(font_id, str(round((q - ip_y).length, 4)))

                    # -- -- -- -- z axis
                    ip_z = intersect_line_plane(
                        q, q + (Vector((0.0, 0.0, 1.0)) * 0.1),
                        Vector((1.0, 0.0, 0.0)), Vector((0.0, 0.0, 1.0)))
                    ip_z_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d, ip_z)

                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glColor4f(0.0, 0.0, 1.0,
                                  context.scene.dt_custom_props.a)
                    bgl.glBegin(bgl.GL_LINES)
                    bgl.glVertex2f(q_loc_2d[0], q_loc_2d[1])
                    bgl.glVertex2f(ip_z_loc_2d[0], ip_z_loc_2d[1])
                    bgl.glEnd()
                    bgl.glDisable(bgl.GL_BLEND)

                    if context.scene.dt_custom_props.b2 == False:
                        loc_3_2d = (q_loc_2d + ip_z_loc_2d) * 0.5
                        bgl.glColor4f(0.0, 0.0, 1.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, loc_3_2d[0] + 4, loc_3_2d[1] + 4,
                                     0)
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)
                        blf.draw(font_id, str(round((q - ip_z).length, 4)))

                    # -- -- -- --
                    if context.scene.dt_custom_props.b2 == True and context.scene.dt_custom_props.b1 == True:
                        blf.size(font_id, font_size,
                                 context.user_preferences.system.dpi)

                        bgl.glColor4f(1.0, 0.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(
                            font_id, q_loc_2d[0] + 4,
                            q_loc_2d[1] + 4 + font_size + 4 + font_size + 4, 0)
                        blf.draw(font_id,
                                 'x ' + str(round((q - ip_x).length, 4)))

                        bgl.glColor4f(0.0, 1.0, 0.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, q_loc_2d[0] + 4,
                                     q_loc_2d[1] + 4 + font_size + 4, 0)
                        blf.draw(font_id,
                                 'y ' + str(round((q - ip_y).length, 4)))

                        bgl.glColor4f(0.0, 0.0, 1.0,
                                      context.scene.dt_custom_props.a)
                        blf.position(font_id, q_loc_2d[0] + 4, q_loc_2d[1] + 4,
                                     0)
                        blf.draw(font_id,
                                 'z ' + str(round((q - ip_z).length, 4)))

            # -- -- -- -- mouse location
            if context.scene.dt_custom_props.b4 == True:

                rgn = context.region  # region
                rgn_3d = context.space_data.region_3d  # region 3d

                bgl.glEnable(bgl.GL_BLEND)
                bgl.glColor4f(1.0, 1.0, 1.0, context.scene.dt_custom_props.a)
                bgl.glBegin(bgl.GL_LINES)
                bgl.glVertex2f(0, dt_buf.y)
                bgl.glVertex2f(dt_buf.x - 15, dt_buf.y)
                bgl.glEnd()
                bgl.glDisable(bgl.GL_BLEND)

                bgl.glEnable(bgl.GL_BLEND)
                bgl.glColor4f(1.0, 1.0, 1.0, context.scene.dt_custom_props.a)
                bgl.glBegin(bgl.GL_LINES)
                bgl.glVertex2f(rgn.width, dt_buf.y)
                bgl.glVertex2f(dt_buf.x + 15, dt_buf.y)
                bgl.glEnd()
                bgl.glDisable(bgl.GL_BLEND)

                bgl.glEnable(bgl.GL_BLEND)
                bgl.glColor4f(1.0, 1.0, 1.0, context.scene.dt_custom_props.a)
                bgl.glBegin(bgl.GL_LINES)
                bgl.glVertex2f(dt_buf.x, 0)
                bgl.glVertex2f(dt_buf.x, dt_buf.y - 15)
                bgl.glEnd()
                bgl.glDisable(bgl.GL_BLEND)

                bgl.glEnable(bgl.GL_BLEND)
                bgl.glColor4f(1.0, 1.0, 1.0, context.scene.dt_custom_props.a)
                bgl.glBegin(bgl.GL_LINES)
                bgl.glVertex2f(dt_buf.x, rgn.height)
                bgl.glVertex2f(dt_buf.x, dt_buf.y + 15)
                bgl.glEnd()
                bgl.glDisable(bgl.GL_BLEND)
                bgl.glDisable(bgl.GL_LINE_STIPPLE)

                t = str(dt_buf.x) + ', ' + str(dt_buf.y)
                lo = region_2d_to_location_3d(context.region,
                                              context.space_data.region_3d,
                                              Vector((dt_buf.x, dt_buf.y)),
                                              Vector((0.0, 0.0, 0.0)))
                t1 = '( ' + str(round(lo[0], 4)) + ', ' + str(round(
                    lo[1], 4)) + ', ' + str(round(lo[2], 4)) + ' )'

                bgl.glColor4f(1.0, 1.0, 1.0, context.scene.dt_custom_props.a)
                blf.position(font_id, dt_buf.x + 15, dt_buf.y + 15, 0)
                blf.size(font_id, 14, context.user_preferences.system.dpi)
                blf.draw(font_id,
                         t1 if context.scene.dt_custom_props.b5 == True else t)

            bgl.glDisable(bgl.GL_LINE_STIPPLE)

            # -- -- -- -- angles
            if context.scene.dt_custom_props.b3 == True:
                list_ek = [[v.index for v in e.verts]
                           for e in bme.verts[list_0[0]].link_edges]
                n1 = len(list_ek)

                for j in range(n1):
                    vec1 = p - bme.verts[[
                        i for i in list_ek[j] if i != list_0[0]
                    ][0]].co.copy()
                    vec2 = p - bme.verts[[
                        i for i in list_ek[(j + 1) % n1] if i != list_0[0]
                    ][0]].co.copy()
                    ang = vec1.angle(vec2)

                    a_loc_2d = location_3d_to_region_2d(
                        context.region, context.space_data.region_3d,
                        mtrx * (((p - (vec1.normalized() * 0.1)) +
                                 (p - (vec2.normalized() * 0.1))) * 0.5))

                    bgl.glColor4f(0.0, 0.757, 1.0,
                                  context.scene.dt_custom_props.a)
                    blf.position(font_id, a_loc_2d[0], a_loc_2d[1], 0)
                    blf.size(font_id, font_size,
                             context.user_preferences.system.dpi)
                    blf.draw(
                        font_id,
                        str(
                            round(ang, 4) if context.scene.dt_custom_props.
                            b6 == True else round(degrees(ang), 2)))

            # -- -- -- -- tool on/off
            bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
            blf.position(font_id, 150, 10, 0)
            blf.size(font_id, 20, context.user_preferences.system.dpi)
            blf.draw(font_id, 'Ruler On')
Example #36
0
    def draw_callback_2d(self, context):
        domain = context.scene.flip_fluid.get_domain_object()
        if domain is None:
            return
        dprops = context.scene.flip_fluid.get_domain_properties()

        if vcu.get_object_hide_viewport(domain):
            return
        if not dprops.debug.display_simulation_grid:
            return

        if not vcu.is_blender_28():
            dlayers = [i for i,v in enumerate(domain.layers) if v]
            slayers = [i for i,v in enumerate(context.scene.layers) if v]
            if not (set(dlayers) & set(slayers)):
                return

        if dprops.debug.grid_display_mode == 'GRID_DISPLAY_SIMULATION':
            isize, jsize, ksize, viewport_dx = dprops.simulation.get_viewport_grid_dimensions()
            _, _, _, simulation_dx = dprops.simulation.get_simulation_grid_dimensions()
        elif dprops.debug.grid_display_mode == 'GRID_DISPLAY_PREVIEW':
            presolution = dprops.simulation.preview_resolution

            """

            isize, jsize, ksize, viewport_dx = dprops.simulation.get_viewport_grid_dimensions(resolution=presolution)
            _, _, _, simulation_dx = dprops.simulation.get_simulation_grid_dimensions(resolution=presolution)
        else:
            isize, jsize, ksize, viewport_dx = dprops.simulation.get_viewport_grid_dimensions()
            _, _, _, simulation_dx = dprops.simulation.get_simulation_grid_dimensions()

        if dprops.debug.grid_display_mode == 'GRID_DISPLAY_MESH':
            isize *= (dprops.surface.subdivisions + 1)
            jsize *= (dprops.surface.subdivisions + 1)
            ksize *= (dprops.surface.subdivisions + 1)
            viewport_dx /= (dprops.surface.subdivisions + 1)
            """

            isize, jsize, ksize, viewport_dx = dprops.simulation.get_viewport_grid_dimensions(resolution=presolution)
            _, _, _, simulation_dx = dprops.simulation.get_simulation_grid_dimensions(resolution=presolution)
        elif dprops.debug.grid_display_mode == 'GRID_DISPLAY_MESH':
            isize, jsize, ksize, simulation_dx = dprops.simulation.get_viewport_grid_dimensions()
            isize *= (dprops.surface.subdivisions + 1)
            jsize *= (dprops.surface.subdivisions + 1)
            ksize *= (dprops.surface.subdivisions + 1)
            simulation_dx /= (dprops.surface.subdivisions + 1)
        elif dprops.debug.grid_display_mode == 'GRID_DISPLAY_FORCE_FIELD':
            isize, jsize, ksize, simulation_dx = dprops.simulation.get_viewport_grid_dimensions()
            reduction = 1
            force_field_quality_str = 'Ultra'
            if dprops.world.force_field_resolution == 'FORCE_FIELD_RESOLUTION_LOW':
                reduction = 4
                force_field_quality_str = 'Low'
            elif dprops.world.force_field_resolution == 'FORCE_FIELD_RESOLUTION_NORMAL':
                reduction = 3
                force_field_quality_str = 'Normal'
            elif dprops.world.force_field_resolution == 'FORCE_FIELD_RESOLUTION_HIGH':
                reduction = 2
                force_field_quality_str = 'High'
            isize = int(math.ceil(isize / reduction))
            jsize = int(math.ceil(jsize / reduction))
            ksize = int(math.ceil(ksize / reduction))
            simulation_dx *= reduction

        width = context.region.width
        if vcu.is_blender_28():
            height = 200
            xstart = context.region.width - 400
        else:
            height = context.region.height
            xstart = 50

        font_id = 0
        if dprops.debug.grid_display_mode == 'GRID_DISPLAY_SIMULATION':
            blf.size(font_id, 20, 72)
            blf.position(font_id, xstart, height - 50, 0)
            blf.draw(font_id, "Simulation Grid")

            blf.size(font_id, 15, 72)
            blf.position(font_id, xstart + 10, height - 80, 0)
            blf.draw(font_id, "Grid Resolution: " + str(isize) + " x " + str(jsize) + " x " + str(ksize))

            dimx = round(simulation_dx * isize, 4)
            dimy = round(simulation_dx * jsize, 4)
            dimz = round(simulation_dx * ksize, 4)
            blf.position(font_id, xstart + 10, height - 105, 0)
            blf.draw(font_id, "Grid Dimensions: " + str(dimx) + "m x " + str(dimy) + "m x " + str(dimz) + "m")

            blf.position(font_id, xstart + 10, height - 130, 0)
            blf.draw(font_id, "Grid Cell Count: " + format(isize*jsize*ksize, ",").replace(",", " "))

            blf.position(font_id, xstart + 10, height - 155, 0)
            blf.draw(font_id, "Grid Cell Width: " + str(round(simulation_dx, 4)) + "m")
        elif dprops.debug.grid_display_mode == 'GRID_DISPLAY_MESH':
            if dprops.surface.compute_chunk_mode == 'COMPUTE_CHUNK_MODE_AUTO':
                compute_chunks = dprops.surface.compute_chunks_auto
            else:
                compute_chunks = dprops.surface.compute_chunks_fixed

            blf.size(font_id, 20, 72)
            blf.position(font_id, xstart, height - 50, 0)
            blf.draw(font_id, "Final Surface Mesh Grid")

            blf.size(font_id, 15, 72)
            blf.position(font_id, xstart + 10, height - 80, 0)
            blf.draw(font_id, "Subdivisions: " + str(dprops.surface.subdivisions))

            blf.position(font_id, xstart + 10, height - 105, 0)
            blf.draw(font_id, "Compute Chunks: " + str(compute_chunks))

            blf.position(font_id, xstart + 10, height - 130, 0)
            blf.draw(font_id, "Grid Resolution: " + str(isize) + " x " + str(jsize) + " x " + str(ksize))

            num_cells = isize*jsize*ksize
            num_cells_str = format(num_cells, ",").replace(",", " ")
            chunk_cells_str = format(math.ceil(num_cells / compute_chunks), ",").replace(",", " ")
            blf.position(font_id, xstart + 10, height - 155, 0)
            blf.draw(font_id, "Grid Cell Count: " + num_cells_str + " (" + chunk_cells_str + " / chunk)")

            blf.position(font_id, xstart + 10, height - 180, 0)
            blf.draw(font_id, "Grid Cell Width: " + str(round(simulation_dx, 4)))
        elif dprops.debug.grid_display_mode == 'GRID_DISPLAY_PREVIEW':
            blf.size(font_id, 20, 72)
            blf.position(font_id, xstart, height - 50, 0)
            blf.draw(font_id, "Preview Surface Mesh Grid")

            blf.size(font_id, 15, 72)
            blf.position(font_id, xstart + 10, height - 80, 0)
            blf.draw(font_id, "Grid Resolution: " + str(isize) + " x " + str(jsize) + " x " + str(ksize))

            num_cells = isize*jsize*ksize
            num_cells_str = format(num_cells, ",").replace(",", " ")
            blf.position(font_id, xstart + 10, height - 105, 0)
            blf.draw(font_id, "Grid Cell Width: " + str(round(simulation_dx, 4)))
        elif dprops.debug.grid_display_mode == 'GRID_DISPLAY_FORCE_FIELD':
            blf.size(font_id, 20, 72)
            blf.position(font_id, xstart, height - 50, 0)
            blf.draw(font_id, "Force Field Grid")

            blf.size(font_id, 15, 72)
            blf.position(font_id, xstart + 10, height - 80, 0)
            blf.draw(font_id, "Force Field Quality: " + force_field_quality_str)

            blf.position(font_id, xstart + 10, height - 105, 0)
            blf.draw(font_id, "Force Field Resolution: " + str(isize) + " x " + str(jsize) + " x " + str(ksize))

            num_cells = isize*jsize*ksize
            num_cells_str = format(num_cells, ",").replace(",", " ")
            blf.position(font_id, xstart + 10, height - 130, 0)
            blf.draw(font_id, "Grid Cell Width: " + str(round(simulation_dx, 4)))
Example #37
0
 def size(size, dpi=None, fontid=None):
     if not dpi: dpi = FontManager.get_dpi()
     return blf.size(FontManager.load(fontid), size, dpi)
Example #38
0
def DRAW_Overlay(self, context):

    np_print('DRAW_Overlay_START', ';', 'NP020RM.flag = ', NP020RM.flag)

    flag = NP020RM.flag
    helper = NP020RM.helper
    angstep = NP020RM.angstep
    region = bpy.context.region
    rv3d = bpy.context.region_data
    rw = region.width
    rh = region.height
    if NP020RM.centerloc == None: centerloc = helper.location
    else: centerloc = NP020RM.centerloc
    qdef = NP020RM.qdef
    ndef = NP020RM.ndef
    alpha_0 = NP020RM.alpha_0
    alpha_1 = NP020RM.alpha_1
    np_print('rw, rh', rw, rh)
    rmin = int(min(rw, rh) / 10)
    if rmin == 0: rmin = 1
    co2d = self.co2d
    if flag in ('RUNTRANSCENTER', 'RUNTRANSSTART'):
        co2d = view3d_utils.location_3d_to_region_2d(region, rv3d,
                                                     helper.location)
    if qdef == None:
        q = get_ro_normal_from_vertical(region, rv3d, co2d)[1]
        n = get_ro_normal_from_vertical(region, rv3d, co2d)[0]
    else:
        q = qdef
        n = ndef
    NP020RM.q = q
    NP020RM.n = n
    #co2d_exp = (event.mouse_region_x, event.mouse_region_y)
    #n_exp = get_ro_normal_from_vertical(region, rv3d, co2d_exp)[0]
    #np_print('co2d, n, q, n_exp', co2d, n, q)

    # writing the dots for circle at center of scene:
    radius = 1
    ang = 0.0
    circle = [(0.0, 0.0, 0.0)]
    while ang < 360.0:
        circle.append(((cos(radians(ang)) * radius),
                       (sin(radians(ang)) * radius), (0.0)))
        ang += 10
    circle.append(
        ((cos(radians(0.0)) * radius), (sin(radians(0.0)) * radius), (0.0)))

    # rotating and translating the circle to user picked angle and place:
    circle = rotate_graphic(circle, q)
    circle = translate_graphic(circle, centerloc)

    rmax = 1
    for i, co in enumerate(circle):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        circle[i] = co
    for i in range(1, 18):
        r = (circle[0] - circle[i]).length
        r1 = (circle[0] - circle[i + 18]).length
        #if (r + r1) > rmax and abs(r - r1) < min(r, r1)/5: rmax = (r+r1)/2
        #if (r + r1) > rmax and abs(r - r1) < min(r, r1)/10: rmax = r + r1
        if (r + r1) > rmax and (r + r1) / 2 < rmin: rmax = (r + r1)
        elif (r + r1) > rmax and (r + r1) / 2 >= rmin:
            rmax = (r + r1) * rmin / (((r + r1) / 2) - ((r + r1) / 2) - rmin)
        rmax = abs(rmax)
        circle[i] = co
    np_print('rmin', rmin)
    np_print('rmax', rmax)
    if flag not in ('RUNTRANSSTART', 'RUNROTEND'):
        fac = (rmin * 2) / rmax
        NP020RM.fac = fac
    else:
        fac = NP020RM.fac

    radius = 1 * fac
    ang = 0.0
    circle = [(0.0, 0.0, 0.0)]
    while ang < 360.0:
        circle.append(((cos(radians(ang)) * radius),
                       (sin(radians(ang)) * radius), (0.0)))
        ang += 10
    circle.append(
        ((cos(radians(0.0)) * radius), (sin(radians(0.0)) * radius), (0.0)))

    if flag == 'RUNTRANSCENTER':
        instruct = 'place center point'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm, CTRL - snap'
        keys_nav = ''
        keys_neg = 'ESC - quit'

        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(90, 0, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, 90, fac, r1, r2, angstep)

    elif flag == 'BGLPLANE':
        instruct = 'choose rotation plane'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm'
        keys_nav = 'MMB / SCROLL - navigate'
        keys_neg = 'ESC - quit'

        ro_hor, isohipse = get_ro_x_from_iso(region, rv3d, co2d, centerloc)
        NP020RM.ro_hor = copy.deepcopy(ro_hor)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(4)
        bgl.glBegin(bgl.GL_POINTS)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(90, 0, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, 90, fac, r1, r2, angstep)

        circle = rotate_graphic(circle, ro_hor)
        walpha = rotate_graphic(walpha, ro_hor)
        wbeta_L = rotate_graphic(wbeta_L, ro_hor)
        wbeta_D = rotate_graphic(wbeta_D, ro_hor)

        circle = rotate_graphic(circle, q)
        walpha = rotate_graphic(walpha, q)
        wbeta_L = rotate_graphic(wbeta_L, q)
        wbeta_D = rotate_graphic(wbeta_D, q)

    elif flag == 'RUNTRANSSTART':
        instruct = 'place start point'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm, CTRL - snap'
        keys_nav = ''
        keys_neg = 'ESC - quit'

        hloc = helper.location
        #np_print('hloc', hloc)
        hlocb = hloc + n
        #np_print('hlocb', hlocb)
        #np_print('centerloc, n', centerloc, n)
        proj_start = mathutils.geometry.intersect_line_plane(
            helper.location, (helper.location + n), centerloc, n)
        NP020RM.proj_start = proj_start
        if proj_start == centerloc:
            proj = centerloc + Vector((0.0, 0.0, 0.001))
        #np_print('proj_start' , proj_start)

        alpha_0, isohipse = get_angle_from_iso_planar(centerloc, n, proj_start)
        alpha_1 = alpha_0
        NP020RM.alpha_0 = alpha_0
        NP020RM.alpha_1 = alpha_1
        np_print('alpha_0', alpha_0)

        ro_hor = NP020RM.ro_hor

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(4)
        bgl.glBegin(bgl.GL_POINTS)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(alpha_1, 0, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, alpha_0, fac, r1, r2, angstep)

        circle = rotate_graphic(circle, ro_hor)
        walpha = rotate_graphic(walpha, ro_hor)
        wbeta_L = rotate_graphic(wbeta_L, ro_hor)
        wbeta_D = rotate_graphic(wbeta_D, ro_hor)

        circle = rotate_graphic(circle, q)
        walpha = rotate_graphic(walpha, q)
        wbeta_L = rotate_graphic(wbeta_L, q)
        wbeta_D = rotate_graphic(wbeta_D, q)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.5, 0.5, 1.0, 1.0)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        points = (helper.location, proj_start, centerloc)
        for co in points:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        co = view3d_utils.location_3d_to_region_2d(region, rv3d, proj_start)
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(14)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex2f(*co)
        bgl.glEnd()

    elif flag == 'RUNROTEND':
        instruct = 'place end point'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm, CTRL - snap'
        keys_nav = ''
        keys_neg = 'ESC - quit'
        for k, v in bpy.context.active_operator.properties.items():
            np_print(k, v)
        alpha_0 = NP020RM.alpha_0_def
        hloc = helper.location
        startloc = NP020RM.startloc
        endloc = helper.location
        proj_start = NP020RM.proj_start
        #np_print('hloc', hloc)
        hlocb = hloc + n
        #np_print('hlocb', hlocb)
        #np_print('centerloc, n', centerloc, n)
        proj_end = mathutils.geometry.intersect_line_plane(
            helper.location, (helper.location + n), centerloc, n)
        if proj_end == centerloc:
            proj_end = centerloc + Vector((0.0, 0.0, 0.001))
        #np_print('proj_end' , proj_end)

        alpha = get_angle_vector_from_vector(centerloc, proj_start, proj_end)
        alpha_1 = alpha_0 + alpha
        np_print('alpha_0', alpha_0)

        ro_hor = NP020RM.ro_hor

        rot_helper_0 = NP020RM.rot_helper_0
        np_print('rot_helper_0 =', rot_helper_0)
        rot_helper_1 = helper.rotation_euler
        np_print('rot_helper_1 =', rot_helper_1)
        alpha_real = get_eul_z_angle_diffffff_in_rotated_system(
            rot_helper_0, rot_helper_1, ndef)
        np_print('alpha_real =', alpha_real)

        delta = (abs(alpha_real) - (360 * int(abs(alpha_real) / 360)))
        if alpha_real >= 0:
            if alpha_0 + delta < 360: alpha_1 = alpha_0 + delta
            else: alpha_1 = delta - (360 - alpha_0)
        else:
            if delta < alpha_0:
                alpha_1 = alpha_0
                alpha_0 = alpha_1 - delta
            else:
                alpha_1 = alpha_0
                alpha_0 = 360 - (delta - alpha_0)

        if alpha_1 == alpha_0: alpha_1 = alpha_0 + 0.001
        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(alpha_1, alpha_0, fac, r1, r2, angstep)
        '''
        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, alpha_0, fac, r1, r2, angstep)
        '''

        circle = rotate_graphic(circle, ro_hor)
        walpha = rotate_graphic(walpha, ro_hor)
        wbeta_L = rotate_graphic(wbeta_L, ro_hor)
        #wbeta_D = rotate_graphic(wbeta_D, ro_hor)

        circle = rotate_graphic(circle, q)
        walpha = rotate_graphic(walpha, q)
        wbeta_L = rotate_graphic(wbeta_L, q)
        #wbeta_D = rotate_graphic(wbeta_D, q)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.5, 0.5, 1.0, 1.0)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        points = (helper.location, proj_end, centerloc, proj_start)
        for co in points:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        co = view3d_utils.location_3d_to_region_2d(region, rv3d, proj_end)
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(14)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex2f(*co)
        bgl.glEnd()

        # NUMERICAL ANGLE:

        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        font_id = 0
        blf.size(font_id, 20, 72)
        ang_pos = view3d_utils.location_3d_to_region_2d(
            region, rv3d, centerloc)
        blf.position(font_id, ang_pos[0] + 2, ang_pos[1] - 2, 0)
        blf.draw(font_id, str(round(alpha_real, 2)))
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        blf.position(font_id, ang_pos[0], ang_pos[1], 0)
        blf.draw(font_id, str(round(alpha_real, 2)))

    # DRAWING START:
    bgl.glEnable(bgl.GL_BLEND)

    # ON-SCREEN INSTRUCTIONS:

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)

    np_print('centerloc', centerloc)
    circle = translate_graphic(circle, centerloc)

    walpha = translate_graphic(walpha, centerloc)
    wbeta_L = translate_graphic(wbeta_L, centerloc)
    if flag is not 'RUNROTEND': wbeta_D = translate_graphic(wbeta_D, centerloc)

    np_print('rv3d', rv3d)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(circle):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        circle[i] = co
    bgl.glEnd()
    np_print('centerloc', centerloc)

    # drawing of walpha contours:
    bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(walpha):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        walpha[i] = co
    bgl.glEnd()
    #np_print('walpha', walpha)
    bgl.glColor4f(0.0, 0.0, 0.0, 0.5)

    # drawing of walpha fields:
    np_print('alpha_0, alpha_1 =', alpha_0, alpha_1)
    if alpha_1 >= alpha_0: alpha = alpha_1 - alpha_0
    else: alpha = alpha_1 + (360 - alpha_0)
    sides = int(alpha / NP020RM.angstep) + 1
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2f(*walpha[0])
    bgl.glVertex2f(*walpha[1])
    bgl.glVertex2f(*walpha[2])
    bgl.glVertex2f(*walpha[(sides * 2) + 1])
    bgl.glEnd()
    for i in range(1, sides):
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*walpha[((sides * 2) + 2) - i])
        bgl.glVertex2f(*walpha[i + 1])
        bgl.glVertex2f(*walpha[2 + i])
        bgl.glVertex2f(*walpha[((sides * 2) + 2) - (i + 1)])
        bgl.glEnd()

    # drawing of wbeta_L contours:
    bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(wbeta_L):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        wbeta_L[i] = co
    bgl.glEnd()
    #np_print('wbeta_L', wbeta_L)
    bgl.glColor4f(0.65, 0.85, 1.0, 0.35)

    # drawing of wbeta_L fields:
    if flag == 'RUNROTEND':
        if alpha_0 >= alpha_1: alpha = alpha_0 - alpha_1
        else: alpha = alpha_0 + (360 - alpha_1)
    else: alpha = 360 - alpha_1
    sides = int(alpha / NP020RM.angstep) + 1
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2f(*wbeta_L[0])
    bgl.glVertex2f(*wbeta_L[1])
    bgl.glVertex2f(*wbeta_L[2])
    bgl.glVertex2f(*wbeta_L[(sides * 2) + 1])
    bgl.glEnd()
    for i in range(1, sides):
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*wbeta_L[((sides * 2) + 2) - i])
        bgl.glVertex2f(*wbeta_L[i + 1])
        bgl.glVertex2f(*wbeta_L[2 + i])
        bgl.glVertex2f(*wbeta_L[((sides * 2) + 2) - (i + 1)])
        bgl.glEnd()

    if flag is not 'RUNROTEND':
        # drawing of wbeta_D contours:
        bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for i, co in enumerate(wbeta_D):
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
            wbeta_D[i] = co
        bgl.glEnd()
        #np_print('wbeta_D', wbeta_D)
        bgl.glColor4f(0.35, 0.6, 0.75, 0.35)

        # drawing of wbeta_D fields:

        alpha = alpha_0
        sides = int(alpha / NP020RM.angstep) + 1
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*wbeta_D[0])
        bgl.glVertex2f(*wbeta_D[1])
        bgl.glVertex2f(*wbeta_D[2])
        bgl.glVertex2f(*wbeta_D[(sides * 2) + 1])
        bgl.glEnd()
        for i in range(1, sides):
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            bgl.glVertex2f(*wbeta_D[((sides * 2) + 2) - i])
            bgl.glVertex2f(*wbeta_D[i + 1])
            bgl.glVertex2f(*wbeta_D[2 + i])
            bgl.glVertex2f(*wbeta_D[((sides * 2) + 2) - (i + 1)])
            bgl.glEnd()

    #ENDING

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Example #39
0
    def hud(dummy, self, context):
        #if getattr(self,'type') :
        if 'type' in dir(self):
            imtool = bpy.context.window_manager.imagetools
            mdl = imtool.modal
            bpy.ops.image.view_all()
            img = active()
            # something to do when fullscreened.. test should be here
            if 2 == 2:
                rev = img.revision()
                if rev.canvas_area != 'off':
                    #if len(self.lastlog) >= 2 : self.log = self.lastlog.pop(0)
                    #else : self.log = self.lastlog[0]
                    evt = self  #.event
                    #print(dir(self.event))
                    imtool = bpy.context.window_manager.imagetools

                    # mouse can be outside of our area so don't use context
                    #area,region = findArea('IMAGE_EDITOR','WINDOW')
                    area = context.area
                    region = context.region
                    area_sx = region.width
                    area_sy = region.height

                    #image_ed, img_ui  = getArea('IMAGE_EDITOR','UI')
                    #img_win  = getRegion(image_ed)
                    #img_prev  = getRegion(image_ed,'PREVIEW')

                    zoom_x = area.spaces[0].zoom[0]
                    zoom_y = area.spaces[0].zoom[1]

                    #print('log : %s last(%s)'%(self.log,self.lastlog))
                    #print('evt : %s  %s'%(evt.type,evt.value))
                    #print(self.lastlog)
                    #print(context.space_data.type)
                    #print(dir(evt))

                    #
                    #if area.type == context.area.type and region.type == context.region.type :
                    x_min, x, x_max = self._regions
                    y_min, y_max = self._regionsy

                    if x < self.mouse_x < x_max and y_min < self.mouse_y < y_max:
                        mouse_x = self.mouse_x - x
                        mouse_y = self.mouse_y - y_min
                    else:
                        mouse_x = False
                        mouse_y = False

                    img_sx, img_sy = img.size
                    img_sx = int(img_sx * zoom_x)
                    img_sy = int(img_sy * zoom_y)

                    img_x0 = int((area_sx - img_sx) * 0.5)
                    img_y0 = int((area_sy - img_sy) * 0.5)

                    offset_x = int(rev.offset_x * zoom_x)
                    offset_y = int(rev.offset_y * zoom_y)

                    width = int(rev.width * zoom_x)
                    height = int(rev.height * zoom_y)

                    blf.size(0, 11, 72)

                    # enable action zones in crop selection box
                    drag = up = down = right = left = False

                    if rev.canvas_area == 'offset':
                        crop_x = img_x0 + min(offset_x, img_sx)
                        crop_sx = max(0, min(img_sx - offset_x, width))

                        crop_sy = min(img_sy, height)
                        crop_y = max(img_y0 - crop_sy,
                                     img_y0 + img_sy - crop_sy - offset_y)
                        if crop_y - img_y0 < 0:
                            crop_sy += crop_y - img_y0
                            crop_y = img_y0

                        txt_offx = offset_x
                        txt_offx_x = crop_x
                        txt_offx_y = crop_y + crop_sy

                        x, y = blf.dimensions(0, '%s' % (offset_y))
                        txt_offy = offset_y
                        txt_offy_x = txt_offx_x - x
                        txt_offy_y = txt_offx_y - y

                        txt_sizx = '%s' % rev.width
                        txt_sizy = '%s' % rev.height

                        drag = up = down = right = left = True

                    else:

                        drag = False

                        txt_offx = ''
                        txt_offy = ''
                        txt_offx_x = 0
                        txt_offx_y = 0
                        txt_offy_x = 0
                        txt_offy_y = 0
                        if rev.canvas_percent:
                            crop_sx = int(
                                min((rev.width * 0.01) * img_sx, img_sx)) + 1
                            crop_sy = int(
                                min((rev.height * 0.01) * img_sy, img_sy)) + 1
                            txt_sizx = '%s%s' % (rev.width, '%')
                            txt_sizy = '%s%s' % (rev.height, '%')
                        else:
                            crop_sx = min(img_sx, width)
                            crop_sy = min(img_sy, height)
                            txt_sizx = '%s' % rev.width
                            txt_sizy = '%s' % rev.height

                        if rev.canvas_area == 'top-left':
                            crop_x = img_x0
                            crop_y = img_y0 + img_sy - crop_sy
                            down = right = True

                        elif rev.canvas_area == 'top-center':
                            crop_x = img_x0 + int((img_sx - crop_sx) * 0.5)
                            crop_y = img_y0 + img_sy - crop_sy
                            down = right = left = True

                        elif rev.canvas_area == 'top-right':
                            crop_x = img_x0 + img_sx - crop_sx
                            crop_y = img_y0 + img_sy - crop_sy
                            down = left = True

                        elif rev.canvas_area == 'center-left':
                            crop_x = img_x0
                            crop_y = img_y0 + int((img_sy - crop_sy) * 0.5)
                            up = down = right = True

                        elif rev.canvas_area == 'center':
                            crop_x = img_x0 + int((img_sx - crop_sx) * 0.5)
                            crop_y = img_y0 + int((img_sy - crop_sy) * 0.5)
                            up = down = right = left = True

                        elif rev.canvas_area == 'center-right':
                            crop_x = img_x0 + img_sx - crop_sx
                            crop_y = img_y0 + int((img_sy - crop_sy) * 0.5)
                            up = down = left = True

                        elif rev.canvas_area == 'bottom-left':
                            crop_x = img_x0
                            crop_y = img_y0
                            up = right = True

                        elif rev.canvas_area == 'bottom-center':
                            crop_x = img_x0 + int((img_sx - crop_sx) * 0.5)
                            crop_y = img_y0
                            up = right = left = True

                        elif rev.canvas_area == 'bottom-right':
                            crop_x = img_x0 + img_sx - crop_sx
                            crop_y = img_y0
                            up = left = True

                    #print(crop_x - img_x0, crop_y - img_y0, crop_sx, crop_sy)

                    x, y = blf.dimensions(0, txt_sizx)
                    txt_sizx_x = crop_x + int((crop_sx - x) * 0.5)
                    txt_sizx_y = crop_y - 11

                    x, y = blf.dimensions(0, txt_sizy)
                    txt_sizy_x = crop_x + crop_sx
                    txt_sizy_y = crop_y + int((crop_sy - y) * 0.5)

                    bgl.glColor4f(0.4, 0.4, 0.4, 0.5)

                    # event
                    blf.position(0, 35, 50, 0)
                    blf.size(0, 13, 72)
                    blf.draw(0, "%s" % (self.log))

                    # timer
                    if mdl.timer:
                        if evt.type == 'TIMER': self.idx = (self.idx + 1) % 4
                        blf.size(0, 11, 72)
                        blf.position(0, 35, 35, 0)
                        blf.draw(
                            0, "timer %1.3f : %s" % (mdl.timer_refresh,
                                                     ('|/-\\')[self.idx]))

                    # is over ?
                    overcrop = False
                    bgl.glColor4f(0.3, 0.7, 0.3, 0.3)
                    if mouse_x:
                        blf.position(0, 35, 20, 0)
                        blf.size(0, 11, 72)
                        blf.draw(
                            0, 'Mx: %s My: %s %s' %
                            (mouse_x, mouse_y, self._regions))
                        if (crop_x < mouse_x < crop_x + crop_sx
                                and crop_y < mouse_y < crop_y + crop_sy):
                            overcrop = True
                            bgl.glColor4f(0.5, 0.7, 0.5, 0.5)

                    # crop selection box
                    bgl.glEnable(bgl.GL_BLEND)
                    bgl.glBegin(bgl.GL_QUADS)
                    drawRectangle(crop_x, crop_y, crop_sx, crop_sy, 0)
                    bgl.glEnd()

                    bgl.glColor4f(1.0, 1.0, 1.0, 1.0)

                    if evt.type in ['MOUSEMOVE', 'TIMER']:
                        if self.log != self.lastlog:
                            self.evttime = time.clock()
                        self.log = self.lastlog
                    else:
                        self.log = self.lastlog = '%s %s' % (evt.type,
                                                             evt.value)
                        self.evttime = time.clock()

                    #if time.clock() - self.evttime > 1 :
                    #    self.log = self.lastlog = ''

                    # drag status change ?
                    if dummy.drag == False and overcrop and self.log == 'LEFTMOUSE PRESS':
                        dummy.drag = True
                        dummy.mouse_xo = mouse_x
                        dummy.mouse_yo = mouse_y

                    elif dummy.drag and self.log == 'LEFTMOUSE RELEASE':
                        dummy.drag = False
                        dummy.last_over_act = ''

                    # define over action
                    stretch = 8
                    over_act = ''
                    if dummy.drag:

                        if rev.canvas_percent and rev.canvas_area != 'offset':
                            percent_x = 100.0 / img_sx
                            percent_y = 100.0 / img_sy
                        else:
                            percent_x = percent_y = 1

                        st_y = False
                        if down and ('down' in dummy.last_over_act
                                     or mouse_y - crop_y < stretch):
                            rev.height = int(
                                ((crop_sy - mouse_y + dummy.mouse_yo) *
                                 percent_y) / zoom_y)
                            st_y = True
                            over_act = 'resize down'

                        elif up and ('up' in dummy.last_over_act
                                     or mouse_y > crop_y + crop_sy - stretch):
                            rev.offset_y = int(
                                (offset_y - mouse_y + dummy.mouse_yo) / zoom_y)
                            rev.height = int(
                                ((crop_sy + mouse_y - dummy.mouse_yo) *
                                 percent_y) / zoom_y)
                            st_y = True
                            over_act = 'resize up'

                        st_x = False
                        if right and ('right' in dummy.last_over_act
                                      or mouse_x > crop_x + crop_sx - stretch):
                            rev.width = int(
                                ((crop_sx + mouse_x - dummy.mouse_xo) *
                                 percent_x) / zoom_x)
                            st_x = True
                            if over_act == '': over_act = 'resize right'
                            else: over_act += '/right'

                        elif left and ('left' in dummy.last_over_act
                                       or mouse_x - crop_x < stretch):
                            #rev.width  = int( ( ( crop_sx * percent_x ) + ( mouse_x - dummy.mouse_xo ) ) / zoom_x )
                            rev.width = int(
                                ((crop_sx - mouse_x + dummy.mouse_xo) *
                                 percent_x) / zoom_x)
                            rev.offset_x = int(
                                (offset_x + mouse_x - dummy.mouse_xo) / zoom_x)
                            st_x = True
                            if over_act == '': over_act = 'resize left'
                            else: over_act += '/left'

                        if drag and ('drag' == dummy.last_over_act or
                                     (st_x == False and st_y == False)):
                            rev.offset_x = int(
                                (offset_x +
                                 (mouse_x - dummy.mouse_xo)) / zoom_x)
                            rev.offset_y = int(
                                (offset_y -
                                 (mouse_y - dummy.mouse_yo)) / zoom_y)
                            over_act = 'drag'

                        dummy.mouse_xo = mouse_x
                        dummy.mouse_yo = mouse_y
                        blf.position(0, 35, 70, 0)
                        blf.draw(0, over_act)
                        dummy.last_over_act = over_act
                        #print(rev.width, crop_sx,percent_x,zoom_x,mouse_x - dummy.mouse_xo )

                    # box selection areas
                    #print(overcrop,over_act)
                    if overcrop or over_act != '':
                        bgl.glEnable(bgl.GL_BLEND)
                        bgl.glBegin(bgl.GL_LINES)
                        bgl.glLineWidth(5)
                        if up:
                            drawLinef(crop_x, crop_y + crop_sy - stretch,
                                      crop_x + crop_sx,
                                      crop_y + crop_sy - stretch)
                        if down:
                            drawLinef(crop_x, crop_y + stretch,
                                      crop_x + crop_sx, crop_y + stretch)
                        if left:
                            drawLinef(crop_x + stretch, crop_y,
                                      crop_x + stretch, crop_y + crop_sy)
                        if right:
                            drawLinef(crop_x + crop_sx - stretch, crop_y,
                                      crop_x + crop_sx - stretch,
                                      crop_y + crop_sy)
                        bgl.glEnd()

                    # crop info
                    if txt_offx != '':
                        blf.position(0, txt_offx_x, txt_offx_y, 0)
                        blf.draw(0, '%s' % (txt_offx))
                        blf.position(0, txt_offy_x, txt_offy_y, 0)
                        blf.draw(0, '%s' % (txt_offy))
                    blf.position(0, txt_sizx_x, txt_sizx_y, 0)
                    blf.draw(0, '%s' % (txt_sizx))
                    blf.position(0, txt_sizy_x, txt_sizy_y, 0)
                    blf.draw(0, '%s' % (txt_sizy))

                else:
                    imtool.showcrop = False
Example #40
0
def draw_callback_px(self, context):
    # circle graphic, text, and slider
    unify_settings = bpy.context.tool_settings.unified_paint_settings
    strength = unify_settings.strength if self.uni_str else self.brush.strength
    size = unify_settings.size if self.uni_size else self.brush.size

    if self.graphic:
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.brushcolor.r, self.brushcolor.g, self.brushcolor.b,
                      strength * 0.25)
        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.circlepoints:
            bgl.glVertex2i(
                int(size * x) + self.cur[0],
                int(size * y) + self.cur[1])
        bgl.glEnd()
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    if self.text != 'NONE' and self.doingstr:
        if self.text == 'MEDIUM':
            fontsize = 11
        elif self.text == 'LARGE':
            fontsize = 22
        else:
            fontsize = 8

        font_id = 0
        blf.size(font_id, fontsize, 72)
        blf.shadow(font_id, 0, 0.0, 0.0, 0.0, 1.0)
        blf.enable(font_id, blf.SHADOW)

        if strength < 0.001:
            text = "0.001"
        else:
            text = str(strength)[0:5]
        textsize = blf.dimensions(font_id, text)

        xpos = self.start[0] + self.offset[0]
        ypos = self.start[1] + self.offset[1]

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.backcolor.r, self.backcolor.g, self.backcolor.b,
                      0.5)

        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.rectpoints:
            bgl.glVertex2i(
                int(textsize[0] * x) + xpos,
                int(textsize[1] * y) + ypos)
        bgl.glEnd()

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

        blf.position(font_id, xpos, ypos, 0)
        blf.draw(font_id, text)

        blf.disable(font_id, blf.SHADOW)

    if self.slider != 'NONE' and self.doingstr:
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.backcolor.r, self.backcolor.g, self.backcolor.b,
                      0.5)

        xpos = self.start[0] + self.offset[0] - self.sliderwidth + (
            32
            if self.text == 'MEDIUM' else 64 if self.text == 'LARGE' else 23)
        ypos = self.start[1] + self.offset[
            1] - self.sliderheight  # + (1 if self.slider != 'SMALL' else 0)

        if strength < 1.0:
            sliderscale = strength
        elif strength > 5.0:
            sliderscale = strength / 10
        elif strength > 2.0:
            sliderscale = strength / 5
        else:
            sliderscale = strength / 2

        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.rectpoints:
            bgl.glVertex2i(
                int(self.sliderwidth * x) + xpos,
                int(self.sliderheight * y) + ypos - 1)
        bgl.glEnd()

        bgl.glColor4f(self.frontcolor.r, self.frontcolor.g, self.frontcolor.b,
                      0.8)

        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.rectpoints:
            bgl.glVertex2i(
                int(self.sliderwidth * x * sliderscale) + xpos,
                int(self.sliderheight * y * 0.75) + ypos)
        bgl.glEnd()

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Example #41
0
def cursor_delta_draw(cls, context):
    cc = context.scene.cursor_control

    draw = 0
    if hasattr(cc, "deltaLocationDraw"):
        draw = cc.deltaLocationDraw
    if hasattr(cc, "deltaEnabled"):
        if (not cc.deltaEnabled[0]):
            draw = 0

    if not draw:
        return

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glShadeModel(bgl.GL_FLAT)
    alpha = 1 - PHI_INV

    offset = ([-4.480736161291701,
               -8.939966636005579], [-0.158097634992133, -9.998750178787843],
              [4.195854066857877,
               -9.077158622037636], [7.718765411993642, -6.357724476147943],
              [9.71288060283854,
               -2.379065025383466], [9.783240669628, 2.070797430975971
                                     ], [7.915909938224691, 6.110513059466902],
              [4.480736161291671,
               8.939966636005593], [0.15809763499209872, 9.998750178787843],
              [-4.195854066857908,
               9.077158622037622], [-7.718765411993573, 6.357724476148025
                                    ], [-9.712880602838549, 2.379065025383433],
              [-9.783240669627993,
               -2.070797430976005], [-7.915909938224757, -6.110513059466818])

    c = Vector(CursorAccess.getCursor())
    p1 = c + Vector(cc.deltaVector)
    locationC = region3d_get_2d_coordinates(context, c)
    location = region3d_get_2d_coordinates(context, p1)
    bgl.glColor4f(0, 1, 1, alpha)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(locationC[0], locationC[1])
    bgl.glVertex2f(location[0], location[1])
    bgl.glEnd()

    #bgl.glColor4f(0, 1, 1, alpha)
    bgl.glBegin(bgl.GL_LINE_LOOP)
    for i in range(14):
        bgl.glVertex2f(location[0] + offset[i][0], location[1] + offset[i][1])
    bgl.glEnd()

    # Crosshair
    offset2 = 20
    offset = 5
    #bgl.glColor4f(0, 1, 1, alpha)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(location[0] - offset2, location[1])
    bgl.glVertex2f(location[0] - offset, location[1])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(location[0] + offset, location[1])
    bgl.glVertex2f(location[0] + offset2, location[1])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(location[0], location[1] - offset2)
    bgl.glVertex2f(location[0], location[1] - offset)
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(location[0], location[1] + offset)
    bgl.glVertex2f(location[0], location[1] + offset2)
    bgl.glEnd()

    # distance to cursor
    blf.size(0, 10, 72)  # Prevent font size to randomly change.
    d = Vector(cc.deltaVector).length
    blf.position(0, location[0] + 10, location[1] + 10, 0)
    blf.draw(0, str(round(d, PRECISION)))
    def __render_text(size, v, s):

        blf.size(0, size, 72)
        blf.position(0, v.x, v.y, 0)
        blf.draw(0, s)
Example #43
0
def draw_callback_light(self, context):
    winman = bpy.data.window_managers['WinMan']
    addon_preferences = get_addon_preferences()
    shortcut = addon_preferences.prefs_offset_shortcut
    isolated = []
    notvisible = []
    hidden = []
    location = []
    oklocation = []
    lamps = []
    lights = []
    meshisolated = []
    meshnotvisible = []
    meshhidden = []
    meshoklocation = []
    mesh = []
    slayers = []
    size = winman.isolatelight_font_size
    space = winman.isolatelight_font_space
    layer = winman.isolatelight_layer_modal
    lampIO = winman.isolatelight_lamp_onoff_modal
    meshIO = winman.isolatelight_meshlight_onoff_modal
    mx = winman.isolatelight_mx
    my = winman.isolatelight_my
    offx = winman.isolatelight_modal_offx
    offsety = winman.isolatelight_modal_offy
    hover = 0
    surlign = (*addon_preferences.prefs_highlight, 1.0)
    wh = (*addon_preferences.prefs_base, 1.0)
    normal = (*addon_preferences.prefs_lamp, 1.0)
    meshnormal = (*addon_preferences.prefs_meshlight, 1.0)
    border = (*addon_preferences.prefs_border, 1.0)
    multsp = space / 10
    multsi = size / 10
    chks = 0
    wdt2 = 0

    overlap = context.user_preferences.system.use_region_overlap
    if bpy.context.area.type == 'VIEW_3D' and overlap == True:
        for r in bpy.context.area.regions:
            if r.type == 'TOOLS':
                wdt2 = r.width - 1
                self.regionwdt = wdt2
                offx = winman.isolatelight_modal_offx + r.width - 1

    #create lamp lists
    if lampIO == True:
        if layer == False:
            for n in bpy.context.scene.objects:
                if n.type == 'LAMP':
                    if n.select == True:
                        chks = 1
                    lights.append(n.name)
                    lamps.append(n.name)
                    new2dCo = location_3d_to_region_2d(context.region, \
                                               context.space_data.region_3d, \
                                               n.location)
                    try:
                        location.append([new2dCo.x, new2dCo.y])
                    except AttributeError:
                        pass
                    if n.hide_render == False:
                        isolated.append(n.name)
                        new2dCo = location_3d_to_region_2d(context.region, \
                                               context.space_data.region_3d, \
                                               n.location)
                        try:
                            oklocation.append([new2dCo.x, new2dCo.y])
                        except AttributeError:
                            pass
                    else:
                        hidden.append(n.name)
                    if n.hide == True:
                        notvisible.append(n.name)
        else:
            scene = bpy.context.scene
            slayers = [
                i for i in range(len(scene.layers)) if scene.layers[i] == True
            ]
            for n in scene.objects:
                if n.type == 'LAMP':
                    if n.select == True:
                        chks = 1
                    for i in range(len(n.layers)):
                        if n.layers[i] == True and i in slayers:
                            lights.append(n.name)
                            lamps.append(n.name)
                            new2dCo = location_3d_to_region_2d(context.region, \
                                                       context.space_data.region_3d, \
                                                       n.location)
                            try:
                                location.append([new2dCo.x, new2dCo.y])
                            except AttributeError:
                                pass
                            if n.hide_render == False:
                                isolated.append(n.name)
                                new2dCo = location_3d_to_region_2d(context.region, \
                                                       context.space_data.region_3d, \
                                                       n.location)
                                try:
                                    oklocation.append([new2dCo.x, new2dCo.y])
                                except AttributeError:
                                    pass
                            else:
                                hidden.append(n.name)
                            if n.hide == True:
                                notvisible.append(n.name)

    #create meshlights lists
    if meshIO == True:
        if layer == False:
            for n in bpy.context.scene.objects:
                if n.type == 'MESH' and n.active_material is not None and n.active_material.use_nodes == True:
                    chkm = 0
                    for node in n.active_material.node_tree.nodes:
                        if node.type == 'EMISSION' and node.mute == False and node.outputs[
                                0].is_linked == True:
                            chkm = 1
                    if chkm == 1:
                        if n.select == True:
                            chks = 1
                        mesh.append(n.name)
                        lamps.append(n.name)
                        new2dCo = location_3d_to_region_2d(context.region, \
                                                   context.space_data.region_3d, \
                                                   n.location)
                        try:
                            location.append([new2dCo.x, new2dCo.y])
                        except AttributeError:
                            pass
                        if n.hide_render == False:
                            meshisolated.append(n.name)
                            new2dCo = location_3d_to_region_2d(context.region, \
                                                   context.space_data.region_3d, \
                                                   n.location)
                            try:
                                meshoklocation.append([new2dCo.x, new2dCo.y])
                            except AttributeError:
                                pass
                        else:
                            meshhidden.append(n.name)
                        if n.hide == True:
                            meshnotvisible.append(n.name)
        else:
            scene = bpy.context.scene
            slayers = [
                i for i in range(len(scene.layers)) if scene.layers[i] == True
            ]
            for n in bpy.context.scene.objects:
                if n.type == 'MESH' and n.active_material is not None and n.active_material.use_nodes == True:
                    chkm = 0
                    for node in n.active_material.node_tree.nodes:
                        if node.type == 'EMISSION' and node.mute == False and node.outputs[
                                0].is_linked == True:
                            chkm = 1
                    if chkm == 1:
                        if n.select == True:
                            chks = 1
                        for i in range(len(n.layers)):
                            if n.layers[i] == True and i in slayers:
                                mesh.append(n.name)
                                lamps.append(n.name)
                                new2dCo = location_3d_to_region_2d(context.region, \
                                                           context.space_data.region_3d, \
                                                           n.location)
                                try:
                                    location.append([new2dCo.x, new2dCo.y])
                                except AttributeError:
                                    pass
                                if n.hide_render == False:
                                    meshisolated.append(n.name)
                                    new2dCo = location_3d_to_region_2d(context.region, \
                                                           context.space_data.region_3d, \
                                                           n.location)
                                    try:
                                        meshoklocation.append(
                                            [new2dCo.x, new2dCo.y])
                                    except AttributeError:
                                        pass
                                else:
                                    meshhidden.append(n.name)
                                if n.hide == True:
                                    meshnotvisible.append(n.name)

    font_id = 0

    base = 60 + offsety
    if lampIO == True:
        if mx < 15 + offx or mx > int(150 * multsi) + offx or my < base + 20:
            self.hover2 = ''
        if winman.isolatelight_unrendered_modal == True:
            if len(hidden) != 0:
                for n in hidden:
                    chk = 0
                    base += int(20 * multsp)
                    blf.position(font_id, 15 + offx, base, 0)
                    blf.size(font_id, int(15 * (size / 10)), 72)
                    if mx > 15 + offx and mx < int(
                            40 *
                            multsi) + offx and my > base and my <= base + 20:
                        bgl.glColor4f(*surlign)
                        for n2 in lights:
                            if n == n2:
                                hover = lamps.index(n2)
                                self.hover2 = "R'''" + n2
                    else:
                        bgl.glColor4f(*wh)
                    blf.draw(font_id, "[U]")

                    blf.position(font_id, int(40 * multsi) + offx, base, 0)
                    if mx >= int(40 * multsi) + offx and mx < int(
                            65 *
                            multsi) + offx and my > base and my <= base + 20:
                        bgl.glColor4f(*surlign)
                        for n2 in lights:
                            if n == n2:
                                hover = lamps.index(n2)
                                self.hover2 = "V'''" + n2
                    else:
                        bgl.glColor4f(*wh)
                    for n2 in notvisible:
                        if n2 == n:
                            chk = 1
                    if chk == 1:
                        blf.draw(font_id, "[H]")
                    else:
                        blf.draw(font_id, "[V]")

                    blf.position(font_id, int(65 * multsi) + offx, base, 0)
                    if mx >= int(65 * multsi) + offx and mx < int(
                            150 *
                            multsi) + offx and my > base and my <= base + 20:
                        bgl.glColor4f(*surlign)
                        for n2 in lights:
                            if n == n2:
                                hover = lamps.index(n2)
                                self.hover2 = n2
                    else:
                        bgl.glColor4f(*wh)
                    blf.draw(font_id, n)

                if my > base + 20:
                    self.hover2 = ''
        if len(hidden) != 0 and len(
                isolated
        ) != 0 and winman.isolatelight_unrendered_modal == True:
            base += int(20 * multsp)
            bgl.glLineWidth(2)
            bgl.glColor4f(*wh)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            bgl.glVertex2f(15 + offx, base)
            bgl.glVertex2f(100 + offx, base)
            bgl.glEnd()

            base -= int(10 * multsp)
        if len(isolated) != 0:
            for n in isolated:
                chk = 0
                base += int(20 * multsp)
                blf.position(font_id, 15 + offx, base, 0)
                blf.size(font_id, int(15 * (size / 10)), 72)
                if mx > 15 + offx and mx < int(
                        40 * multsi) + offx and my > base and my <= base + 20:
                    bgl.glColor4f(*surlign)
                    for n2 in lights:
                        if n == n2:
                            hover = lamps.index(n2)
                            self.hover2 = "R'''" + n2
                else:
                    bgl.glColor4f(*wh)
                blf.draw(font_id, "[R]")

                blf.position(font_id, int(40 * multsi) + offx, base, 0)
                if mx >= int(40 * multsi) + offx and mx < int(
                        65 * multsi) + offx and my > base and my <= base + 20:
                    bgl.glColor4f(*surlign)
                    for n2 in lights:
                        if n == n2:
                            hover = lamps.index(n2)
                            self.hover2 = "V'''" + n2
                else:
                    bgl.glColor4f(*wh)
                for n2 in notvisible:
                    if n2 == n:
                        chk = 1
                if chk == 1:
                    blf.draw(font_id, "[H]")
                else:
                    blf.draw(font_id, "[V]")

                blf.position(font_id, int(65 * multsi) + offx, base, 0)
                if mx >= int(65 * multsi) + offx and mx < int(
                        150 * multsi) + offx and my > base and my <= base + 20:
                    bgl.glColor4f(*surlign)
                    for n2 in lights:
                        if n == n2:
                            hover = lamps.index(n2)
                            self.hover2 = n2
                else:
                    bgl.glColor4f(*wh)
                blf.draw(font_id, n)

            if my > base + 20:
                self.hover2 = ''

        if len(hidden
               ) != 0 and winman.isolatelight_unrendered_modal == True or len(
                   isolated) != 0:
            bgl.glColor4f(*wh)
            base += int(23 * multsp)
            blf.position(font_id, 15 + offx, base, 0)
            blf.size(font_id, int(13 * (size / 10)), 72)
            blf.draw(font_id, "Lamps")
            base += int(20 * multsp)

    # screen meshlights
    if meshIO == True:
        #        if mx<15 or mx>int(150*multsi) or my<base+20:
        #            self.hover2=''
        if winman.isolatelight_unrendered_modal == True:
            if len(meshhidden) != 0:
                for n in meshhidden:
                    chk = 0
                    base += int(20 * multsp)
                    blf.position(font_id, 15 + offx, base, 0)
                    blf.size(font_id, int(15 * (size / 10)), 72)
                    if mx > 15 + offx and mx < int(
                            40 *
                            multsi) + offx and my > base and my <= base + 20:
                        bgl.glColor4f(*surlign)
                        for n2 in mesh:
                            if n == n2:
                                hover = lamps.index(n2)
                                self.hover2 = "R'''" + n2
                    else:
                        bgl.glColor4f(*wh)
                    blf.draw(font_id, "[U]")

                    blf.position(font_id, int(40 * multsi) + offx, base, 0)
                    if mx >= int(40 * multsi) + offx and mx < int(
                            65 *
                            multsi) + offx and my > base and my <= base + 20:
                        bgl.glColor4f(*surlign)
                        for n2 in mesh:
                            if n == n2:
                                hover = lamps.index(n2)
                                self.hover2 = "V'''" + n2
                    else:
                        bgl.glColor4f(*wh)
                    for n2 in meshnotvisible:
                        if n2 == n:
                            chk = 1
                    if chk == 1:
                        blf.draw(font_id, "[H]")
                    else:
                        blf.draw(font_id, "[V]")

                    blf.position(font_id, int(65 * multsi) + offx, base, 0)
                    if mx >= int(65 * multsi) + offx and mx < int(
                            150 *
                            multsi) + offx and my > base and my <= base + 20:
                        bgl.glColor4f(*surlign)
                        for n2 in mesh:
                            if n == n2:
                                hover = lamps.index(n2)
                                self.hover2 = n2
                    else:
                        bgl.glColor4f(*wh)
                    blf.draw(font_id, n)

                if my > base + 20:
                    self.hover2 = ''
        if len(meshhidden) != 0 and len(
                meshisolated
        ) != 0 and winman.isolatelight_unrendered_modal == True:
            base += int(20 * multsp)
            bgl.glLineWidth(2)
            bgl.glColor4f(*wh)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            bgl.glVertex2f(15 + offx, base)
            bgl.glVertex2f(100 + offx, base)
            bgl.glEnd()

            base -= int(10 * multsp)
        if len(meshisolated) != 0:
            for n in meshisolated:
                chk = 0
                base += int(20 * multsp)
                blf.position(font_id, 15 + offx, base, 0)
                blf.size(font_id, int(15 * (size / 10)), 72)
                if mx > 15 + offx and mx < int(
                        40 * multsi) + offx and my > base and my <= base + 20:
                    bgl.glColor4f(*surlign)
                    for n2 in mesh:
                        if n == n2:
                            hover = lamps.index(n2)
                            self.hover2 = "R'''" + n2
                else:
                    bgl.glColor4f(*wh)
                blf.draw(font_id, "[R]")

                blf.position(font_id, int(40 * multsi) + offx, base, 0)
                if mx >= int(40 * multsi) + offx and mx < int(
                        65 * multsi) + offx and my > base and my <= base + 20:
                    bgl.glColor4f(*surlign)
                    for n2 in mesh:
                        if n == n2:
                            hover = lamps.index(n2)
                            self.hover2 = "V'''" + n2
                else:
                    bgl.glColor4f(*wh)
                for n2 in meshnotvisible:
                    if n2 == n:
                        chk = 1
                if chk == 1:
                    blf.draw(font_id, "[H]")
                else:
                    blf.draw(font_id, "[V]")

                blf.position(font_id, int(65 * multsi) + offx, base, 0)
                if mx >= int(65 * multsi) + offx and mx < int(
                        150 * multsi) + offx and my > base and my <= base + 20:
                    bgl.glColor4f(*surlign)
                    for n2 in mesh:
                        if n == n2:
                            hover = lamps.index(n2)
                            self.hover2 = n2
                else:
                    bgl.glColor4f(*wh)
                blf.draw(font_id, n)

            if my > base + 20:
                self.hover2 = ''

        if len(meshhidden
               ) != 0 and winman.isolatelight_unrendered_modal == True or len(
                   meshisolated) != 0:
            bgl.glColor4f(*wh)
            base += int(23 * multsp)
            blf.position(font_id, 15 + offx, base, 0)
            blf.size(font_id, int(13 * (size / 10)), 72)
            blf.draw(font_id, "MeshLights")

    if chks == 1 or winman.isolatelight_on_off == True:
        base += int(40 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(20 * (size / 10)), 72)
        if mx > 15 + offx and mx < int(
                150 * multsi) + offx and my > base and my <= base + 20:
            bgl.glColor4f(*surlign)
            self.hover2 = 'isolate'
            hover = -1
        else:
            bgl.glColor4f(*wh)
        if winman.isolatelight_on_off == True:
            blf.draw(font_id, "De Isolate")
        else:
            blf.draw(font_id, "Isolate")

    if my > base + 20:
        self.hover2 = ''

    if layer == True:
        bgl.glColor4f(*wh)
        base += int(25 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "Active Layers Only")

    if winman.isolatelight_help_modal == True:
        bgl.glColor4f(*wh)
        base += int(40 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "Esc to Quit")

        base += int(20 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "Ctrl + Shift + Left Click to Add lamp to selection")

        base += int(20 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "Ctrl + Left Click to Interact")

        if shortcut == True:
            base += int(20 * multsp)
            blf.position(font_id, 15 + offx, base, 0)
            blf.size(font_id, int(13 * (size / 10)), 72)
            blf.draw(font_id, "Ctrl + Alt to Move texts")

        base += int(20 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "[U] - Unrendered")

        base += int(20 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "[R] - Rendered")

        base += int(20 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "[H] - Hidden")

        base += int(20 * multsp)
        blf.position(font_id, 15 + offx, base, 0)
        blf.size(font_id, int(13 * (size / 10)), 72)
        blf.draw(font_id, "[V] - Visible")

    if lampIO == True or meshIO == True:
        # 50% alpha, 2 pixel width line
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(*normal)
        lw = 4 // 2
        bgl.glLineWidth(lw * 2)

        bgl.glLineWidth(lw)
        l = 15
        if lampIO == True:
            for n in oklocation:
                bgl.glColor4f(*normal)
                bgl.glBegin(bgl.GL_LINE_STRIP)
                x = n[0]
                y = n[1]
                #for x, y in location:
                bgl.glVertex2f(x - l, y + l)
                bgl.glVertex2f(x - l, y - l)
                bgl.glVertex2f(x + l, y - l)
                bgl.glVertex2f(x + l, y + l)
                bgl.glVertex2f(x - l, y + l)
                bgl.glEnd()
        if meshIO == True:
            for n in meshoklocation:
                bgl.glColor4f(*meshnormal)
                bgl.glBegin(bgl.GL_LINE_STRIP)
                x = n[0]
                y = n[1]
                #for x, y in location:
                bgl.glVertex2f(x - l, y + l)
                bgl.glVertex2f(x - l, y - l)
                bgl.glVertex2f(x + l, y - l)
                bgl.glVertex2f(x + l, y + l)
                bgl.glVertex2f(x - l, y + l)
                bgl.glEnd()
        if self.hover2 != '' and self.hover2 != 'isolate':
            for n in location:
                if hover == location.index(n):
                    bgl.glColor4f(*surlign)
                    bgl.glBegin(bgl.GL_LINE_STRIP)
                    x = n[0]
                    y = n[1]
                    #for x, y in location:
                    bgl.glVertex2f(x - l, y + l)
                    bgl.glVertex2f(x - l, y - l)
                    bgl.glVertex2f(x + l, y - l)
                    bgl.glVertex2f(x + l, y + l)
                    bgl.glVertex2f(x - l, y + l)
                    bgl.glEnd()

    # draw outline of screen
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(*border)
    lw = 4 // 2
    bgl.glLineWidth(lw * 2)

    r = context.region

    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2i(lw + wdt2, lw)
    bgl.glVertex2i(r.width - lw, lw)
    bgl.glVertex2i(r.width - lw, r.height - lw)
    bgl.glVertex2i(lw + wdt2, r.height - lw)
    bgl.glVertex2i(lw + wdt2, lw)
    bgl.glEnd()
Example #44
0
def drawObjTextArray(text, corner, pos_x, pos_y):
    vieportInfoProps = bpy.context.scene.vieportInfo
    mode = bpy.context.object.mode
    font_id = 0
    height = bpy.context.region.height
    width = bpy.context.region.width
    txt_width = []
    list_line_width = []
    blf.size(font_id, vieportInfoProps.text_font_size, 72)
    x_offset = 0
    y_offset = 0
    line_height = (blf.dimensions(font_id, "M")[1] * 1.45)
    x = 0
    y = 0

    for command in text:
        if len(command) == 2:
            Text, Color = command
            text_width, text_height = blf.dimensions(font_id, Text)
            txt_width.append(text_width)

    if corner == '1' or corner == '3':
        x = pos_x

    else:
        if mode == 'OBJECT' and vieportInfoProps.obj_use and vieportInfoProps.multi_obj_enabled and (
                len(bpy.context.selected_objects) >= 2):
            count_obj = len(bpy.context.selected_objects)
            len_list = len(txt_width)  # count of item in the list
            count_item = int(len_list / count_obj)  # count of item by object
            i = 0
            start = 0
            end = count_item
            list_text = []

            for item in txt_width:
                while i < count_obj:
                    list_text.append(txt_width[start:start + end])
                    start += end
                    i += 1
            for item in list_text:
                list_line_width.append(sum(item[:]))
            x = width - (max(list_line_width) + pos_x)
        else:
            if txt_width:
                for label, value in zip(txt_width[0::2], txt_width[1::2]):
                    l_width = label + value
                    list_line_width.append(l_width)
                x = width - (max(list_line_width) + pos_x)

    if corner == '1' or corner == '2':
        y = height - pos_y

    else:
        if mode == 'OBJECT' and vieportInfoProps.obj_use and vieportInfoProps.multi_obj_enabled and (
                len(bpy.context.selected_objects) >= 2):
            line_count = len(bpy.context.selected_objects)
            y = pos_y + (line_height * line_count)
        else:
            line_count = text.count("Carriage return")
            y = pos_y + (line_height * line_count)

    for command in text:
        if len(command) == 2:
            Text, Color = command
            bgl.glColor3f(*Color)
            text_width, text_height = blf.dimensions(font_id, Text)
            blf.position(font_id, (x + x_offset), (y + y_offset), 0)
            blf.draw(font_id, Text)
            x_offset += text_width

        else:
            x_offset = 0
            y_offset -= line_height
Example #45
0
def draw_custom_2d_elements():
    context = bpy.context

    font_id = 0  # TODO: Need to find out how best to get this.
    blf.size(font_id, 12, 72)

    (prefab_locators, collision_locators,
     model_locators) = _get_custom_visual_elements()

    if not prefab_locators and \
            not collision_locators and \
            not model_locators:
        return

    glColor3f(
        context.scene.scs_props.info_text_color[0],
        context.scene.scs_props.info_text_color[1],
        context.scene.scs_props.info_text_color[2],
    )

    region = context.region
    region3d = context.space_data.region_3d

    region_mid_width = region.width / 2.0
    region_mid_height = region.height / 2.0

    # VARS FOR PROJECTION
    perspective_matrix = region3d.perspective_matrix.copy()

    region_data = (perspective_matrix, region_mid_width, region_mid_height)

    # LOCATOR NAMES
    if context.scene.scs_props.display_info == 'locnames':
        if prefab_locators:
            for key, obj in prefab_locators.items():
                mat = obj.matrix_world
                _primitive.draw_text(key, font_id,
                                     Vector((mat[0][3], mat[1][3], mat[2][3])),
                                     region_data)

        if collision_locators:
            for key, obj in collision_locators.items():
                mat = obj.matrix_world
                _primitive.draw_text(key, font_id,
                                     Vector((mat[0][3], mat[1][3], mat[2][3])),
                                     region_data)

        if model_locators:
            for key, obj in model_locators.items():
                mat = obj.matrix_world
                _primitive.draw_text(key, font_id,
                                     Vector((mat[0][3], mat[1][3], mat[2][3])),
                                     region_data)

    # LOCATOR COMPREHENSIVE INFO
    elif context.scene.scs_props.display_info == 'locinfo':
        if prefab_locators:
            for key, obj in prefab_locators.items():
                mat = obj.matrix_world
                textlines = [
                    '"' + key + '"',
                    str(obj.scs_props.locator_type + " - " +
                        obj.scs_props.locator_prefab_type)
                ]

                if obj.scs_props.locator_prefab_type == 'Control Node':
                    textlines.append(
                        str("Node Index: " +
                            str(obj.scs_props.locator_prefab_con_node_index)))
                    if 1:  # TODO
                        textlines.append(str("Assigned Points: " + str(0)))
                elif obj.scs_props.locator_prefab_type == 'Spawn Point':
                    textlines.append(
                        str("Type: " +
                            str(obj.scs_props.locator_prefab_spawn_type)))
                elif obj.scs_props.locator_prefab_type == 'Traffic Semaphore':
                    textlines.append(
                        str("ID: " +
                            str(obj.scs_props.locator_prefab_tsem_id)))
                    # if obj.scs_props.locator_prefab_tsem_model != '':
                    # textlines.append(str("Model: " + str(obj.scs_props.locator_prefab_tsem_model)))
                    if obj.scs_props.locator_prefab_tsem_profile != '':
                        textlines.append(
                            str("Profile: " +
                                str(obj.scs_props.locator_prefab_tsem_profile))
                        )
                    if obj.scs_props.locator_prefab_tsem_type != '0':
                        textlines.append(
                            str("Type: " +
                                str(obj.scs_props.locator_prefab_tsem_type)))
                    textlines.append(
                        str("G: " + str(obj.scs_props.locator_prefab_tsem_gm) +
                            " - O: " +
                            str(obj.scs_props.locator_prefab_tsem_om1) +
                            " - R: " +
                            str(obj.scs_props.locator_prefab_tsem_rm)))
                    if obj.scs_props.locator_prefab_tsem_cyc_delay != 0:
                        textlines.append(
                            str("Cycle Delay: " + str(
                                obj.scs_props.locator_prefab_tsem_cyc_delay)))
                    textlines.append(
                        str("Activation: " +
                            str(obj.scs_props.locator_prefab_tsem_activation)))
                    if obj.scs_props.locator_prefab_tsem_ai_only:
                        textlines.append("AI Only")
                elif obj.scs_props.locator_prefab_type == 'Navigation Point':
                    # if obj.scs_props.locator_prefab_np_speed_limit != 0:
                    # textlines.append(str(str(obj.scs_props.locator_prefab_np_speed_limit) + " km/h"))
                    if obj.scs_props.locator_prefab_np_boundary != 'no':
                        textlines.append(
                            str("Lane " +
                                str(obj.scs_props.locator_prefab_np_boundary)))
                    textlines.append(
                        str("B. Node: " +
                            str(obj.scs_props.locator_prefab_np_boundary_node))
                    )
                    if obj.scs_props.locator_prefab_np_traffic_light != '-1':
                        textlines.append(
                            str("T. Light ID: " +
                                str(obj.scs_props.
                                    locator_prefab_np_traffic_light)))
                elif obj.scs_props.locator_prefab_type == 'Map Point':
                    if obj.scs_props.locator_prefab_mp_road_over:
                        textlines.append("Road Over")
                    if obj.scs_props.locator_prefab_mp_no_outline:
                        textlines.append("No Outline")
                    if obj.scs_props.locator_prefab_mp_no_arrow:
                        textlines.append("No Arrow")
                    if obj.scs_props.locator_prefab_mp_prefab_exit:
                        textlines.append("Prefab Exit")
                    textlines.append(
                        str("Road Size: " +
                            str(obj.scs_props.locator_prefab_mp_road_size)))
                    if obj.scs_props.locator_prefab_mp_road_offset != '0m':
                        textlines.append(
                            str("Offset: " + str(
                                obj.scs_props.locator_prefab_mp_road_offset)))
                    if obj.scs_props.locator_prefab_mp_custom_color != 'none':
                        textlines.append(
                            str("Color: " + str(
                                obj.scs_props.locator_prefab_mp_custom_color)))
                    if obj.scs_props.locator_prefab_mp_assigned_node != 'none':
                        textlines.append(
                            str("Node: " +
                                str(obj.scs_props.
                                    locator_prefab_mp_assigned_node)))
                    des_nodes = "Destination Nodes:"
                    if obj.scs_props.locator_prefab_mp_des_nodes_0:
                        des_nodes += " 0"
                    if obj.scs_props.locator_prefab_mp_des_nodes_1:
                        des_nodes += " 1"
                    if obj.scs_props.locator_prefab_mp_des_nodes_2:
                        des_nodes += " 2"
                    if obj.scs_props.locator_prefab_mp_des_nodes_3:
                        des_nodes += " 3"
                    if des_nodes != "Destination Nodes:":
                        textlines.append(des_nodes)
                    if obj.scs_props.locator_prefab_mp_des_nodes_ct:
                        textlines.append("Custom Target")
                elif obj.scs_props.locator_prefab_type == 'Trigger Point':
                    if obj.scs_props.locator_prefab_tp_action != '':
                        textlines.append(
                            str("Action: " +
                                str(obj.scs_props.locator_prefab_tp_action)))
                    textlines.append(
                        str("Range: " +
                            str(obj.scs_props.locator_prefab_tp_range)))
                    if obj.scs_props.locator_prefab_tp_reset_delay != 0:
                        textlines.append(
                            str("Reset Delay: " + str(
                                obj.scs_props.locator_prefab_tp_reset_delay)))
                    if obj.scs_props.locator_prefab_tp_sphere_trigger:
                        textlines.append("Sphere Trigger")
                    if obj.scs_props.locator_prefab_tp_partial_activ:
                        textlines.append("Partial Activation")
                    if obj.scs_props.locator_prefab_tp_onetime_activ:
                        textlines.append("One-Time Activation")
                    if obj.scs_props.locator_prefab_tp_manual_activ:
                        textlines.append("Manual Activation")

                for textline_i, textline in enumerate(textlines):
                    y_pos = (
                        (len(textlines) * 15) / 2) + (textline_i * -15) - 7
                    _primitive.draw_text(
                        textline, font_id,
                        Vector((mat[0][3], mat[1][3], mat[2][3])), region_data,
                        0, y_pos)

        if collision_locators:
            for key, obj in collision_locators.items():
                mat = obj.matrix_world
                textlines = [
                    '"' + key + '"',
                    str(obj.scs_props.locator_type + " - " +
                        obj.scs_props.locator_collider_type),
                    str("Mass: " + str(obj.scs_props.locator_collider_mass))
                ]

                # if obj.scs_props.locator_collider_centered:
                # textlines.append("Locator Centered")
                if obj.scs_props.locator_collider_margin != 0:
                    textlines.append(
                        str("Margin: " +
                            str(obj.scs_props.locator_collider_margin)))

                for textline_i, textline in enumerate(textlines):
                    y_pos = (
                        (len(textlines) * 15) / 2) + (textline_i * -15) - 7
                    _primitive.draw_text(
                        textline, font_id,
                        Vector((mat[0][3], mat[1][3], mat[2][3])), region_data,
                        0, y_pos)

        if model_locators:
            for key, obj in model_locators.items():
                mat = obj.matrix_world
                textlines = [
                    '"' + key + '"',
                    str(obj.scs_props.locator_type),
                    str(obj.scs_props.locator_model_hookup)
                ]

                if obj.scs_props.locator_show_preview_model:
                    textlines.append(
                        str(obj.scs_props.locator_preview_model_path))

                for textline_i, textline in enumerate(textlines):
                    y_pos = (
                        (len(textlines) * 15) / 2) + (textline_i * -15) - 7
                    _primitive.draw_text(
                        textline, font_id,
                        Vector((mat[0][3], mat[1][3], mat[2][3])), region_data,
                        0, y_pos)

    # LOCATOR SPEED LIMITS
    elif context.scene.scs_props.display_info == 'locspeed':
        if prefab_locators:
            for key, obj in prefab_locators.items():
                if obj.scs_props.locator_prefab_type == 'Navigation Point':
                    if obj.scs_props.locator_prefab_np_speed_limit != 0:
                        mat = obj.matrix_world
                        _primitive.draw_text(
                            str(
                                str(obj.scs_props.locator_prefab_np_speed_limit
                                    ) + " km/h"), font_id,
                            Vector((mat[0][3], mat[1][3], mat[2][3])),
                            region_data)

    # LOCATOR BOUNDARY NODES
    elif context.scene.scs_props.display_info == 'locnodes':
        if prefab_locators:
            for key, obj in prefab_locators.items():
                if obj.scs_props.locator_prefab_type == 'Navigation Point':
                    mat = obj.matrix_world
                    _primitive.draw_text(
                        str(obj.scs_props.locator_prefab_np_boundary_node),
                        font_id, Vector(
                            (mat[0][3], mat[1][3], mat[2][3])), region_data)

    # LOCATOR BOUNDARY LANES
    elif context.scene.scs_props.display_info == 'loclanes':
        if prefab_locators:
            for key, obj in prefab_locators.items():
                if obj.scs_props.locator_prefab_type == 'Navigation Point':
                    if obj.scs_props.locator_prefab_np_boundary != 'no':
                        mat = obj.matrix_world
                        _primitive.draw_text(
                            str(obj.scs_props.locator_prefab_np_boundary),
                            font_id, Vector((mat[0][3], mat[1][3], mat[2][3])),
                            region_data)
Example #46
0
    def _draw_browser(self, context):
        """OpenGL drawing code for the BROWSING state."""

        window_region = self._window_region(context)
        content_width = window_region.width - ITEM_MARGIN_X * 2
        content_height = window_region.height - ITEM_MARGIN_Y * 2

        content_x = ITEM_MARGIN_X
        content_y = context.area.height - ITEM_MARGIN_Y - TARGET_ITEM_HEIGHT

        col_count = content_width // TARGET_ITEM_WIDTH

        item_width = (content_width - (col_count * ITEM_PADDING_X)) / col_count
        item_height = TARGET_ITEM_HEIGHT

        block_width = item_width + ITEM_PADDING_X
        block_height = item_height + ITEM_MARGIN_Y

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 0.6)
        bgl.glRectf(0, 0, window_region.width, window_region.height)

        if self.current_display_content:
            bottom_y = float('inf')

            # The -1 / +2 are for extra rows that are drawn only half at the top/bottom.
            first_item_idx = max(
                0,
                int(-self.scroll_offset // block_height - 1) * col_count)
            items_per_page = int(content_height // item_height + 2) * col_count
            last_item_idx = first_item_idx + items_per_page

            for item_idx, item in enumerate(self.current_display_content):
                x = content_x + (item_idx % col_count) * block_width
                y = content_y - (item_idx //
                                 col_count) * block_height - self.scroll_offset

                item.update_placement(x, y, item_width, item_height)

                if first_item_idx <= item_idx < last_item_idx:
                    # Only draw if the item is actually on screen.
                    item.draw(
                        highlighted=item.hits(self.mouse_x, self.mouse_y))

                bottom_y = min(y, bottom_y)
            self.scroll_offset_space_left = window_region.height - bottom_y
            self.scroll_offset_max = (self.scroll_offset -
                                      self.scroll_offset_space_left +
                                      0.25 * block_height)

        else:
            font_id = 0
            text = "Communicating with Blender Cloud"
            bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
            blf.size(font_id, 20, 72)
            text_width, text_height = blf.dimensions(font_id, text)
            blf.position(font_id,
                         content_x + content_width * 0.5 - text_width * 0.5,
                         content_y - content_height * 0.3 + text_height * 0.5,
                         0)
            blf.draw(font_id, text)

        bgl.glDisable(bgl.GL_BLEND)
Example #47
0
def draw_focus_HUD(context, color=(1, 1, 1), alpha=1, width=2):
    if context.space_data.overlay.show_overlays:
        region = context.region
        view = context.space_data

        # only draw when actually in local view, this prevents it being drawn when switing workspace, which doesn't sync local view
        if view.local_view:

            # draw border

            coords = [(width, width), (region.width - width, width),
                      (region.width - width, region.height - width),
                      (width, region.height - width)]
            indices = [(0, 1), (1, 2), (2, 3), (3, 0)]

            shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
            shader.bind()
            shader.uniform_float("color", (*color, alpha / 4))

            bgl.glEnable(bgl.GL_BLEND)

            bgl.glLineWidth(width)

            batch = batch_for_shader(shader,
                                     'LINES', {"pos": coords},
                                     indices=indices)
            batch.draw(shader)

            # draw title

            # check if title needs to be offset down due to the header position
            area = context.area
            headers = [r for r in area.regions if r.type == 'HEADER']

            scale = context.preferences.view.ui_scale
            offset = 4

            if headers:
                header = headers[0]

                # only offset when the header is on top and when show_region_tool_header is disabled
                if area.y - header.y and not view.show_region_tool_header:
                    offset += int(25 * scale)

            title = "Focus Level: %d" % len(context.scene.M3.focus_history)

            stashes = True if context.active_object and getattr(
                context.active_object, 'MM', False) and getattr(
                    context.active_object.MM, 'stashes') else False
            center = (region.width /
                      2) + (scale * 100) if stashes else region.width / 2

            font = 1
            fontsize = int(12 * scale)

            blf.size(font, fontsize, 72)
            blf.color(font, *color, alpha)
            blf.position(font, center - int(60 * scale),
                         region.height - offset - int(fontsize), 0)

            blf.draw(font, title)
Example #48
0
 def font_size(id=0, size=11, dpi=None):
     if dpi is None:
         dpi = bpy.context.user_preferences.system.dpi
     blf.size(id, size, dpi)
Example #49
0
def draw_callback_px(self, context):
    font_id = 0  # XXX, need to find out how best to get this.

    region = context.region

    # Tente de positionner le texte au milieu de la fenetre (à refaire)
    xt = int(region.width / 2.0)
    yt = 70

    # Position et affichage du texte du mode en cours avec les infos dessous (Voir pour mieux centrer le texte)
    blf.position(font_id, xt - blf.dimensions(font_id, "CREATE")[0], 65 + yt,
                 0)
    blf.size(font_id, 20, 82)
    bgl.glColor4f(0.900, 0.4, 0.00, 1.0)
    blf.draw(font_id, "CREATE")

    bgl.glLineWidth(2)
    bgl.glColor4f(0.900, 0.4, 0.00, 1.0)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2i(int(xt - blf.dimensions(font_id, "CREATE")[0] + 0), 55 + yt)
    bgl.glVertex2i(int(xt - blf.dimensions(font_id, "CREATE")[0] + 200),
                   55 + yt)
    bgl.glEnd()

    # Selon le mode, l'ecriture change de largeur donc le centre est décalé. Ca permet de "réparer" les erreurs.
    xt = xt - blf.dimensions(font_id, "CREATE")[0]

    # Affichage des infos
    blf.size(font_id, 20, 50)
    blf.position(font_id, xt + 15, 35 + yt, 0)
    bgl.glColor4f(0.912, 0.919, 0.994, 1.0)
    if (self.CreateMode == 0):
        blf.draw(font_id, "Type Rectangle [SPACE]")
    if (self.CreateMode == 1):
        blf.draw(font_id, "Type Circle [SPACE]")
    if (self.CreateMode == 2):
        if (self.Closed == False):
            blf.draw(font_id, "Type Line [SPACE] ([C] to close geometry)")
        else:
            blf.draw(font_id,
                     "Type closed Line [SPACE] ([C] to open geometry) ")

    if (self.CreateMode == 0):
        blf.size(font_id, 20, 50)
        blf.position(font_id, xt + 15, 15 + yt, 0)
        bgl.glColor4f(0.912, 0.919, 0.994, 1.0)
        blf.draw(font_id, "Dimension (MouseMove)")
        blf.position(font_id, xt + 15, -5 + yt, 0)
        bgl.glColor4f(0.912, 0.919, 0.994, 1.0)
        blf.draw(font_id, "Move all (Alt + MouseMove)")

    if (self.CreateMode == 1):
        blf.size(font_id, 20, 50)
        blf.position(font_id, xt + 15, 15 + yt, 0)
        bgl.glColor4f(0.912, 0.919, 0.994, 1.0)
        blf.draw(font_id, "Rotation (Ctrl + MouseWheel)")
        blf.position(font_id, xt + 15, -5 + yt, 0)
        blf.draw(font_id, "Definition (MouseWheel)")
        blf.position(font_id, xt + 15, -25 + yt, 0)
        blf.draw(font_id, "Move all (Alt + MouseMove)")

    if (self.CreateMode == 2):
        blf.size(font_id, 20, 50)
        blf.position(font_id, xt + 15, 15 + yt, 0)
        bgl.glColor4f(0.912, 0.919, 0.994, 1.0)
        blf.draw(font_id, "New point (Left Mouse)")
        blf.position(font_id, xt + 15, -5 + yt, 0)
        blf.draw(font_id, "Move all (Alt + MouseMove)")
        blf.position(font_id, xt + 15, -25 + yt, 0)
        blf.draw(font_id, "Incremental (Ctrl)")

    # Mode, couleur et largeur des lignes
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.812, 0.519, 0.094, 0.5)
    bgl.glLineWidth(2)

    # Permet de smoother les points pour les arrondir
    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    if (self.bDone):
        # Affichage des primitives selon le type de découpe choisie

        if (len(self.mouse_path) > 1):
            x0 = self.mouse_path[0][0]
            y0 = self.mouse_path[0][1]
            x1 = self.mouse_path[1][0]
            y1 = self.mouse_path[1][1]

        # Affichage de la ligne de coupe
        if (self.CreateMode == 2):
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for x, y in self.mouse_path:
                bgl.glVertex2i(x + self.xpos, y + self.ypos)
            bgl.glEnd()

            bgl.glPointSize(6)
            bgl.glBegin(bgl.GL_POINTS)
            for x, y in self.mouse_path:
                bgl.glVertex2i(x + self.xpos, y + self.ypos)
            bgl.glEnd()

        # Affichage du rectange de découpe
        if (self.CreateMode == 0):
            bgl.glColor4f(0.812, 0.519, 0.094, 0.5)
            # Selon si on appuie sur SHIFT, le rectangle est plein ou pas
            bgl.glBegin(bgl.GL_QUADS)
            bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
            bgl.glVertex2i(x1 + self.xpos, y0 + self.ypos)
            bgl.glVertex2i(x1 + self.xpos, y1 + self.ypos)
            bgl.glVertex2i(x0 + self.xpos, y1 + self.ypos)
            bgl.glEnd()

            bgl.glPointSize(6)
            bgl.glColor4f(0.812, 0.519, 0.094, 1.0)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
            bgl.glVertex2i(x1 + self.xpos, y0 + self.ypos)
            bgl.glVertex2i(x1 + self.xpos, y1 + self.ypos)
            bgl.glVertex2i(x0 + self.xpos, y1 + self.ypos)
            bgl.glEnd()

        # Affichage du cercle
        if (self.CreateMode == 1):
            DEG2RAD = 3.14159 / 180
            v0 = mathutils.Vector(
                (self.mouse_path[0][0], self.mouse_path[0][1], 0))
            v1 = mathutils.Vector(
                (self.mouse_path[1][0], self.mouse_path[1][1], 0))
            v0 -= v1
            radius = self.mouse_path[1][0] - self.mouse_path[0][0]
            DEG2RAD = 3.14159 / (180 / self.stepAngle[self.step])
            if (self.ctrl):
                shift = (3.14159 /
                         (360 / self.stepAngle[self.step])) * self.stepRotation
            else:
                shift = (self.mouse_path[1][1] - self.mouse_path[0][1]) / 50

            # Selon si on appuie sur SHIFT, le cercle est plein ou pas
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
            for i in range(0, int(360 / self.stepAngle[self.step])):
                degInRad = i * DEG2RAD
                bgl.glVertex2i(
                    x0 + self.xpos + int(math.cos(degInRad + shift) * radius),
                    y0 + self.ypos + int(math.sin(degInRad + shift) * radius))
            bgl.glVertex2i(x0 + self.xpos + int(math.cos(0 + shift) * radius),
                           y0 + self.ypos + int(math.sin(0 + shift) * radius))
            bgl.glEnd()

    # Opengl par défaut
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    bgl.glDisable(bgl.GL_POINT_SMOOTH)
Example #50
0
def draw_callback_px(self, context): 
    wm = context.window_manager 
    sc = context.scene 
  
    if not wm.polycount_run: 
        return
  
    font_size  = sc.polycount_font_size 
    pos_x, pos_y = get_display_location(context) 
  
    # draw text in the 3d-view 
    # ======================== 
    blf.size(0, sc.polycount_font_size, 72) 
    r, g, b = sc.polycount_font_color 
    bgl.glColor3f(r, g, b) 
  
    view3dId = get_space_id(context.space_data) 
      
#    text = "All               Obj              Sel"
#    blf.position(0, pos_x + 15, pos_y, 0)
#    blf.draw(0, text)    
#    

######## vertex Drawing
    
    if sc.show_vertex_count == True:
        text = "V"
        blf.position(0, pos_x , pos_y, 0)
        blf.draw(0, text)

        if vert_count_all == True:
            all_vert_count = polyCountOperator.all_edge_count.get(view3dId, -1)
            if all_vert_count > 0:
                text = format(all_tri_count, ',d')
                text3width = blf.dimensions(0, text)[0] 

                blf.position(0, pos_x + 135 , pos_y , 0) 
                blf.draw(0, text)               
            else:
                text = "0"  	  
                blf.position(0, pos_x + 135, pos_y , 0) 
                blf.draw(0, text)
        else:
            text = "X"
            blf.position(0, pos_X, pos_y - 20, 0)
            blf.draw(o,text)

        if vert_count_obj == True:
            obj_vert_count = polyCountOperator.all_edge_count.get(view3dId, -1)
            if obj_vert_count > 0:
                text = format(obj_vert_count, ',d')
                text3width = blf.dimensions(0, text)[0] 

                blf.position(0, pos_x + 135 , pos_y , 0) 
                blf.draw(0, text)
            else:
                text = "0"  	  
                blf.position(0, pos_x + 135, pos_y , 0) 
                blf.draw(0, text)
        else:
            text = "X"
            blf.position(0, pos_X, pos_y - 20, 0)
            blf.draw(o,text)			

        if vert_count_sel == True:
            sel_vert_count = polyCountOperator.all_edge_count.get(view3dId, -1)
            if sel_vert_count > 0:
                text = format(sel_vert_count, ',d')
                text3width = blf.dimensions(0, text)[0] 

                blf.position(0, pos_x + 135 , pos_y , 0) 
                blf.draw(0, text)
            else:
                text = "0"  	  
                blf.position(0, pos_x + 135, pos_y , 0) 
                blf.draw(0, text)
        else:
            text = "X"
            blf.position(0, pos_X, pos_y - 20, 0)
            blf.draw(o,text)	
def draw_text(self, context):
    font_id = 0
    blf.position(font_id, 15, 30, 0)
    blf.size(font_id, 12, 72)
    blf.draw(font_id, "ray_origin " + str(len(self.stored_points)))
Example #52
0
def draw_callback_px(self, context):
    # esto se calcula cada pasada de dibujado del viewport:

    display = []

    font_id = font_info["font_id"]
    
    x = 19
    toolbarWidth = bpy.context.area.regions[1].width

    offsetTextInTop = 86
    yOffset = bpy.context.area.height - offsetTextInTop

    fontSize = 11
    blf.size(font_id, fontSize, 72)
    
    # sombra:
    # el level tiene que ser 3, 5 o 0
    level = 5
    r = 0.0
    g = 0.0
    b = 0.0
    a = 0.9
    
    blf.enable(font_id , blf.SHADOW )
    blf.shadow(font_id, level, r, g, b, a)
    blf.shadow_offset(font_id, 1, -1)
    
    engines = {
        'BLENDER_EEVEE' : 'Eevee',
        'BLENDER_WORKBENCH' : 'Workbench',
        'CYCLES' : 'Cycles'
    }

    re = 'Engine: ' + engines.get(bpy.context.scene.render.engine)
    display.append(re)

    view_layer = bpy.context.view_layer
    stats = bpy.context.scene.statistics(view_layer).split("|")

    if bpy.context.mode == 'OBJECT':
        ss = stats[2:5]
        ss.append(stats[-2])
        stats = ss
    elif bpy.context.mode == 'EDIT_MESH':
        ss = stats[1:6]
        stats = ss
    elif bpy.context.mode == 'SCULPT':
        ss = stats[1:4]
        ss.append(stats[-2])
        stats = ss
    else:
        stats = []

    if len(stats) > 0:
        display = display + stats

    if engines.get(bpy.context.scene.render.engine) == 'Cycles':
        area = next(area for area in bpy.context.screen.areas if area.type == 'VIEW_3D')
        space = next(space for space in area.spaces if space.type == 'VIEW_3D')
        if space.shading.type == 'RENDERED': 
            rendered = 20
        else:
            rendered = 0
    else:
        rendered = 0

    if bpy.context.space_data.overlay.show_overlays:
        if bpy.context.space_data.overlay.show_text:
            for counter, value in enumerate(display):
                # print(value)
                value = value.replace(" ","")
                value = value.replace(":",": ")
                # print(value)
                increment = (20*counter)
                blf.position(font_id, x+toolbarWidth, yOffset-increment-rendered, 0)
                blf.draw(font_id, value)
def draw_callback_px(self, context):
    allocate_main_ui(self, context)

    shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
    shader.bind()

    addon_prefs = context.preferences.addons[__package__].preferences

    # main window background
    main_window = self.areas["Main Window"]
    outline_color = addon_prefs.qcd_ogl_widget_menu_back_outline
    background_color = addon_prefs.qcd_ogl_widget_menu_back_inner
    draw_rounded_rect(main_window,
                      shader,
                      outline_color[:] + (1, ),
                      outline=True)
    draw_rounded_rect(main_window, shader, background_color)

    # draw window title
    window_title = self.areas["Window Title"]
    x = window_title["vert"][0]
    y = window_title["vert"][1]
    h = window_title["height"]
    text = window_title["value"]
    text_color = addon_prefs.qcd_ogl_widget_menu_back_text
    font_id = 0
    blf.position(font_id, x, y, 0)
    blf.size(font_id, int(h), 72)
    blf.color(font_id, text_color[0], text_color[1], text_color[2], 1)
    blf.draw(font_id, text)

    # refresh shader - not sure why this is needed
    shader.bind()

    in_tooltip_area = False
    tooltip_slot_idx = None

    for num in range(20):
        slot_num = num + 1
        qcd_slot_name = qcd_slots.get_name(f"{slot_num}")
        if qcd_slot_name:
            qcd_laycol = layer_collections[qcd_slot_name]["ptr"]
            collection_objects = qcd_laycol.collection.objects
            selected_objects = qcd_operators.get_move_selection()
            active_object = qcd_operators.get_move_active()
            button_area = self.areas[f"Button {slot_num}"]

            # colors
            button_color = addon_prefs.qcd_ogl_widget_tool_inner
            icon_color = addon_prefs.qcd_ogl_widget_tool_text
            if not qcd_laycol.exclude:
                button_color = addon_prefs.qcd_ogl_widget_tool_inner_sel
                icon_color = addon_prefs.qcd_ogl_widget_tool_text_sel

            if mouse_in_area(self.mouse_pos, button_area):
                in_tooltip_area = True
                tooltip_slot_idx = slot_num

                mod = 0.1

                if button_color[0] + mod > 1 or button_color[
                        1] + mod > 1 or button_color[2] + mod > 1:
                    mod = -mod

                button_color = (button_color[0] + mod, button_color[1] + mod,
                                button_color[2] + mod, button_color[3])

            # button roundness
            tl = tr = bl = br = 0
            rounding = 5

            if num < 10:
                if not qcd_slots.contains(idx=f"{num+2}"):
                    tr = rounding

                if not qcd_slots.contains(idx=f"{num}"):
                    tl = rounding
            else:
                if not qcd_slots.contains(idx=f"{num+2}"):
                    br = rounding

                if not qcd_slots.contains(idx=f"{num}"):
                    bl = rounding

            if num in [0, 5]:
                tl = rounding
            elif num in [4, 9]:
                tr = rounding
            elif num in [10, 15]:
                bl = rounding
            elif num in [14, 19]:
                br = rounding

            # draw button
            outline_color = addon_prefs.qcd_ogl_widget_tool_outline
            draw_rounded_rect(button_area,
                              shader,
                              outline_color[:] + (1, ),
                              tl,
                              tr,
                              bl,
                              br,
                              outline=True)
            draw_rounded_rect(button_area, shader, button_color, tl, tr, bl,
                              br)

            # ACTIVE OBJECT
            if active_object and active_object in selected_objects and active_object.name in collection_objects:
                active_object_indicator = self.areas[
                    f"Button {slot_num} Active Object Indicator"]

                vertices = get_circle_coords(active_object_indicator)
                shader.uniform_float("color", icon_color[:] + (1, ))
                batch = batch_for_shader(shader, 'TRI_FAN', {"pos": vertices})

                bgl.glEnable(bgl.GL_BLEND)

                batch.draw(shader)

                bgl.glDisable(bgl.GL_BLEND)

            # SELECTED OBJECTS
            elif not set(selected_objects).isdisjoint(collection_objects):
                selected_object_indicator = self.areas[
                    f"Button {slot_num} Selected Object Indicator"]

                alpha = addon_prefs.qcd_ogl_selected_icon_alpha
                vertices = get_circle_coords(selected_object_indicator)
                shader.uniform_float("color", icon_color[:] + (alpha, ))
                batch = batch_for_shader(shader, 'LINE_STRIP',
                                         {"pos": vertices})

                bgl.glLineWidth(2 * scale_factor())
                bgl.glEnable(bgl.GL_BLEND)
                bgl.glEnable(bgl.GL_LINE_SMOOTH)
                bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

                batch.draw(shader)

                bgl.glDisable(bgl.GL_LINE_SMOOTH)
                bgl.glDisable(bgl.GL_BLEND)

            # OBJECTS
            elif collection_objects:
                object_indicator = self.areas[
                    f"Button {slot_num} Object Indicator"]

                alpha = addon_prefs.qcd_ogl_objects_icon_alpha
                vertices, indices = get_coords(object_indicator)
                shader.uniform_float("color", icon_color[:] + (alpha, ))
                batch = batch_for_shader(shader,
                                         'TRIS', {"pos": vertices},
                                         indices=indices)

                bgl.glEnable(bgl.GL_BLEND)

                batch.draw(shader)

                bgl.glDisable(bgl.GL_BLEND)

        # X ICON
        else:
            X_icon = self.areas[f"X_icon {slot_num}"]
            X_icon_color = addon_prefs.qcd_ogl_widget_menu_back_text

            vertices, indices = get_x_coords(X_icon)
            shader.uniform_float("color", X_icon_color[:] + (1, ))
            batch = batch_for_shader(shader,
                                     'TRIS', {"pos": vertices},
                                     indices=indices)

            bgl.glEnable(bgl.GL_BLEND)
            bgl.glEnable(bgl.GL_POLYGON_SMOOTH)
            bgl.glHint(bgl.GL_POLYGON_SMOOTH_HINT, bgl.GL_NICEST)

            batch.draw(shader)

            bgl.glDisable(bgl.GL_POLYGON_SMOOTH)
            bgl.glDisable(bgl.GL_BLEND)

    if in_tooltip_area:
        if self.draw_tooltip:
            slot_name = qcd_slots.get_name(f"{tooltip_slot_idx}")
            slot_string = f"QCD Slot {tooltip_slot_idx}: \"{slot_name}\"\n"
            hotkey_string = "  * Shift+LMB - Toggle objects\' slot."

            draw_tooltip(self, context, shader,
                         f"{slot_string}{hotkey_string}")

            self.hover_time = None

        else:
            if not self.hover_time:
                self.hover_time = time.time()
Example #54
0
    def format_and_wrap_text(self):
        '''
        '''
        blf.size(0, self.text_size, self.text_dpi)

        # remove \r characters (silly windows machines!)
        self.raw_text = self.raw_text.replace('\r', '')

        #TODO text size settings?
        useful_width = self.width - 2 * self.border
        #print('>>> useful width = % 8.1f' % useful_width)

        # special case: no newlines and we fit already!
        if '\n' not in self.raw_text and self.txt_width(
                self.raw_text) < useful_width:
            self.text_lines = [self.raw_text]
            return

        def split_word(line):
            '''
            splits off first word, including any leading spaces
            '''
            if not line: return (None, None)
            sp = (line[0] == ' ')
            for i, c in enumerate(line):
                if c == ' ':
                    if not sp: return (line[:i], line[i:])
                    continue
                sp = False
            return (line, '')

        def wrap_line(line):
            '''
            takes a string, returns a list of strings, corresponding to wrapped
            text of the specified pixel width, given current BLF settings
            '''

            line = line.rstrip()  # ignore right whitespace

            if self.txt_width(line) < useful_width:
                # no need to wrap!
                lines = [line]
                #for line in lines:
                #    print('>>> line width = % 8.1f: %s' % (self.txt_width(line), line))
                return lines

            lines = []
            working = ""
            while line:
                word, line = split_word(line)
                if self.txt_width(working + word) < useful_width:
                    working += word
                else:
                    # adding word is too wide!
                    # start new row
                    lines += [working]
                    working = '  ' + word.strip(
                    )  # lead with exactly two spaces
            lines += [working]

            #for line in lines:
            #    print('>>> line width = % 8.1f: %s' % (self.txt_width(line), line))

            return lines

        self.text_lines = []
        for line in self.raw_text.split('\n'):
            self.text_lines += wrap_line(line)

        self.fit_box_height_to_text_lines()
        self.fit_box_width_to_text_lines()
Example #55
0
    def draw_to_viewport(view_min, view_max, show_extra, label_counter,
                         tilegrid, sprytile_data, cursor_loc, region, rv3d,
                         middle_btn, context):
        """Draw the offscreen texture into the viewport"""

        # Prepare some data that will be used for drawing
        grid_size = SprytileGui.loaded_grid.grid
        tile_sel = SprytileGui.loaded_grid.tile_selection
        padding = SprytileGui.loaded_grid.padding
        margin = SprytileGui.loaded_grid.margin
        is_pixel = sprytile_utils.grid_is_single_pixel(SprytileGui.loaded_grid)

        # Draw work plane
        SprytileGui.draw_work_plane(grid_size, sprytile_data, cursor_loc,
                                    region, rv3d, middle_btn)

        # Setup GL for drawing the offscreen texture
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, SprytileGui.texture)
        # Backup texture filter
        old_mag_filter = Buffer(bgl.GL_INT, [1])
        bgl.glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                                old_mag_filter)
        # Set texture filter
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            bgl.GL_NEAREST)
        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glEnable(bgl.GL_BLEND)

        # Draw the preview tile
        if middle_btn is False:
            SprytileGui.draw_preview_tile(context, region, rv3d)

        # Calculate actual view size
        view_size = int(view_max.x - view_min.x), int(view_max.y - view_min.y)

        # Save the original scissor box, and then set new scissor setting
        scissor_box = bgl.Buffer(bgl.GL_INT, [4])
        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
        bgl.glScissor(
            int(view_min.x) + scissor_box[0],
            int(view_min.y) + scissor_box[1], view_size[0], view_size[1])

        # Draw the tile select UI
        SprytileGui.draw_tile_select_ui(view_min, view_max, view_size,
                                        SprytileGui.tex_size, grid_size,
                                        tile_sel, padding, margin, show_extra,
                                        is_pixel)

        # restore opengl defaults
        bgl.glScissor(scissor_box[0], scissor_box[1], scissor_box[2],
                      scissor_box[3])
        bgl.glLineWidth(1)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            old_mag_filter[0])

        # Draw label
        if label_counter > 0:
            import math

            def ease_out_circ(t, b, c, d):
                t /= d
                t -= 1
                return c * math.sqrt(1 - t * t) + b

            font_id = 0
            font_size = 16
            pad = 5
            box_pad = font_size + (pad * 2)
            fade = label_counter
            fade = ease_out_circ(fade, 0, SprytileGui.label_frames,
                                 SprytileGui.label_frames)
            fade /= SprytileGui.label_frames

            bgl.glColor4f(0.0, 0.0, 0.0, 0.75 * fade)
            bgl.glBegin(bgl.GL_QUADS)
            uv = [(0, 0), (0, 1), (1, 1), (1, 0)]
            vtx = [(view_min.x, view_max.y),
                   (view_min.x, view_max.y + box_pad),
                   (view_max.x, view_max.y + +box_pad),
                   (view_max.x, view_max.y)]
            for i in range(4):
                glTexCoord2f(uv[i][0], uv[i][1])
                glVertex2f(vtx[i][0], vtx[i][1])
            bgl.glEnd()

            bgl.glColor4f(1.0, 1.0, 1.0, 1.0 * fade)
            blf.size(font_id, font_size, 72)

            x_pos = view_min.x + pad
            y_pos = view_max.y + pad

            label_string = "%dx%d" % (tilegrid.grid[0], tilegrid.grid[1])
            if tilegrid.name != "":
                label_string = "%s - %s" % (label_string, tilegrid.name)
            blf.position(font_id, x_pos, y_pos, 0)
            blf.draw(font_id, label_string)

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_TEXTURE_2D)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Example #56
0
    def text(self, text, arg1=0, arg2=0, arg3=0):
        x = 0
        y = 0
        z = 0
        rx = 0
        ry = 0
        rz = 0

        if type(arg1) is mathutils.Vector():
            x = arg1.x
            y = arg1.y
            z = arg1.z
            if type(arg2) is mathutils.Vector():
                rx = arg2.x
                ry = arg2.y
                rz = arg2.z

        elif type(arg1) is bge.types.KX_GameObject or type(arg1) is str:
            if type(arg1) is str:
                arg1 = self.getObjectByName(arg1)
            if arg1 is not 0:
                o = self.getPosition(arg1)
                x = o.x
                y = o.y
                z = o.z
                # translation vector
                if type(arg2) is mathutils.Vector():
                    x += arg2.x
                    y += arg2.y
                    z += arg2.z
                # rotation vector
                if type(arg3) is mathutils.Vector():
                    rx = arg3.x
                    ry = arg3.y
                    rz = arg3.z

        elif type(arg1) is float and type(arg2) is float and type(
                arg3) is float:
            x = arg1
            y = arg2
            z = arg3

        elif type(arg1) is int and type(arg2) is int and type(arg3) is int:
            x = arg1
            y = arg2
            z = arg3

        width = bge.render.getWindowWidth()
        height = bge.render.getWindowHeight()
        ratiow = 1. / width
        ratioh = 1. / height
        bgl.glPushMatrix()
        bgl.glTranslatef(x, y, z)
        #TODO transform angles to matrix!
        # bgl.glRotate( rx,ry,rz )
        bgl.glScalef(ratiow, ratioh, 0)
        blf.position(self.font, 0, 0, 0)
        blf.size(self.font, self.tsize, 300)
        bgl.glColor3f(self.tcolor.x, self.tcolor.y, self.tcolor.z)
        blf.draw(self.font, text)
        bgl.glPopMatrix()
Example #57
0
def draw_gems(self, context, ratio_w=1, ratio_h=1, gamma_corr=False):

    if gamma_corr:
        _c = gamma_correction
    else:
        _c = lambda x: x

    view_normal = self.region_3d.view_rotation @ Vector((0.0, 0.0, 1.0))

    if self.region_3d.is_perspective:
        angle_thold = pi / 1.8
        view_loc = self.region_3d.view_matrix.inverted().translation
    else:
        angle_thold = pi / 2.0
        center_xy = (self.region.width / 2.0, self.region.height / 2.0)
        view_loc = region_2d_to_origin_3d(self.region, self.region_3d, center_xy)

    from_scene_scale = unit.Scale(context).from_scene
    depsgraph = context.evaluated_depsgraph_get()
    gems = []
    app = gems.append

    for dup in depsgraph.object_instances:

        if dup.is_instance:
            ob = dup.instance_object.original
        else:
            ob = dup.object.original

        if "gem" not in ob or (self.use_select and not ob.select_get()):
            continue

        ob_stone = ob["gem"]["stone"]
        ob_cut = ob["gem"]["cut"]
        ob_size = tuple(round(x, 2) for x in from_scene_scale(ob.dimensions, batch=True))

        size_fmt, color = self.view_data.get((ob_stone, ob_cut, ob_size), (None, None))

        if color is None:
            continue

        mat = dup.matrix_world.copy()
        dist_from_view = (mat.translation - view_loc).length
        app((dist_from_view, ob, mat, size_fmt, color))

    shader = gpu.shader.from_builtin("2D_UNIFORM_COLOR")
    fontid = 0
    blf.size(fontid, self.prefs.view_font_size_gem_size, 72)
    blf.color(fontid, 0.0, 0.0, 0.0, 1.0)

    gems.sort(key=operator.itemgetter(0), reverse=True)

    for _, ob, mat, size_fmt, color in gems:

        # Shape
        # -----------------------------

        ob_eval = ob.evaluated_get(depsgraph)
        me = ob_eval.to_mesh()
        me.transform(mat)
        verts = me.vertices

        shader.bind()
        shader.uniform_float("color", _c(color))

        for poly in me.polygons:
            if view_normal.angle(poly.normal) < angle_thold:
                cos = [
                    loc_3d_to_2d(self.region, self.region_3d, verts[v].co, ratio_w, ratio_h)
                    for v in poly.vertices
                ]
                batch = batch_for_shader(shader, "TRI_FAN", {"pos": cos})
                batch.draw(shader)

        ob_eval.to_mesh_clear()

        # Size
        # -----------------------------

        loc_x, loc_y = loc_3d_to_2d(self.region, self.region_3d, mat.translation, ratio_w, ratio_h)
        dim_x, dim_y = blf.dimensions(fontid, size_fmt)

        blf.position(fontid, loc_x - dim_x / 2, loc_y - dim_y / 2, 0.0)
        blf.draw(fontid, size_fmt)
Example #58
0
 def init_text(self):
     blf.size(2, 16, 72)
     blf.color(2, 1.0, 1.0, 1.0, 1.0)
Example #59
0
def draw_tris(region, rv3d, context):
    divs = 24  # verts per fan.
    n = 3  # ratio of shortest edge.

    def get_tri_coords(object_list):
        # replace for empties code.
        coordlist = [obj.location for obj in object_list]
        return coordlist

    def get_angle_rad(set_of_coords):
        coord1, coord2, coord3 = set_of_coords
        angle_rad = (coord1 - coord2).angle(coord3 - coord2)
        angle_deg = degrees(angle_rad)
        return angle_rad, angle_deg

    # if 3 empties selected
    coord1, coord2, coord3 = get_tri_coords(context.selected_objects)

    # measure angle between
    angle1 = [coord3, coord1, coord2]
    angle2 = [coord1, coord2, coord3]
    angle3 = [coord2, coord3, coord1]

    edge1 = (coord1 - coord2).length
    edge2 = (coord2 - coord3).length
    edge3 = (coord3 - coord1).length
    shortest_edge = min(edge1, edge2, edge3)
    radial_d = shortest_edge / n

    def make_fan_poly_from_edges(angle_object, radius):
        coordinate_1, shared_co, coordinate_2 = angle_object

        # get length of edge, lerp it , place a point at radial distance (pointN)
        len1 = (coordinate_1 - shared_co).length
        len2 = (coordinate_2 - shared_co).length
        tlerp1 = 1 / (len1 / radius)
        tlerp2 = 1 / (len2 / radius)
        point1 = shared_co.lerp(coordinate_1, tlerp1)
        point2 = shared_co.lerp(coordinate_2, tlerp2)

        # place imaginary line between (point1, point2)
        radial_collection = []
        radial_collection.append(shared_co)

        # start from point1, place temp point (1/24)*i
        # collect points. check all points for distance to angle_point.
        rate = 1 / divs
        for notch in range(divs + 1):
            new_vec = point1.lerp(point2, rate * notch)
            # move new vec away from shared point until the distance is radius.
            new_vec_len = (new_vec - shared_co).length
            lerp_distance = radius / new_vec_len
            radial_point = shared_co.lerp(new_vec, lerp_distance)
            radial_collection.append(radial_point)

        radial_collection.append(shared_co)

        # make polygon
        return radial_collection

    bgl.glEnable(bgl.GL_BLEND)  # enable blending
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

    angle_list = [angle1, angle2, angle3]
    for item in angle_list:
        polyline = make_fan_poly_from_edges(item, radial_d)

        #can be modified per polyline
        bgl.glColor4f(0.103, 0.3, 0.6, 0.4)

        bgl.glBegin(bgl.GL_POLYGON)
        for segment in polyline:
            scr_pixel = loc3d2d(region, rv3d, segment)
            bgl.glVertex2f(*scr_pixel)

        bgl.glEnd()

    # get text.
    for item in angle_list:

        bgl.glColor4f(0.83, 0.8, 0.9, 0.7)
        angrad, angdeg = get_angle_rad(item)
        polyline = make_fan_poly_from_edges(item, radial_d)

        # find coordinate to place the text
        cpoint1 = polyline[0]
        midpoint = floor(len(polyline) / 2)
        cpoint2 = polyline[midpoint]
        cmidway = cpoint1.lerp(cpoint2, 0.5)
        scr_coord = loc3d2d(region, rv3d, cmidway)

        # round both text
        angrad_round = round(angrad, ANG_ROUND)
        angdeg_round = round(angdeg, DEG_ROUND)
        str_angrad = str(angrad_round)
        str_angdeg = str(angdeg_round)
        combined_string = str_angrad + " , " + str_angdeg

        # get length of text, place text .5 of length to the left of the coord.
        font_id = 0
        blf.size(font_id, 12, 72)

        text_width, text_height = blf.dimensions(font_id, combined_string)
        x_pos = text_width / 2

        blf.position(font_id, scr_coord[0] - x_pos, scr_coord[1], 0)
        blf.draw(font_id, combined_string)

    return
Example #60
0
def draw_measurements_callback(self, context):
    sce = context.scene

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            loc_y -= OFFSET_Y

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

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

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

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

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

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

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

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

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

            if len(context.selected_objects) > 2:
                return


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

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

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

                obj1, obj2 = context.selected_objects

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

            elif (obj):
                # One object selected.

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

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

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

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

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

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

                obj1, obj2 = context.selected_objects

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

                sce.measure_panel_volume1 = volume1
                sce.measure_panel_volume2 = volume2

            elif (obj):
                # One object selected.

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

                sce.measure_panel_volume1 = volume1