Пример #1
0
def drawTriangle(triangle, linethickness, linecolor, fillcolor, drawpoints=False, pointcolor=None):
    bgl.glEnable(bgl.GL_BLEND);
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA);
    bgl.glEnable(bgl.GL_LINE_SMOOTH);
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST);
    
#     for co in triangle:
    bgl.glColor4f(*fillcolor);
    bgl.glBegin(bgl.GL_TRIANGLES);
    
    for coord in triangle:
        bgl.glVertex3f(*coord); 
    bgl.glEnd();
    
    bgl.glColor4f(*linecolor);
    bgl.glLineWidth(linethickness);
    bgl.glBegin(bgl.GL_LINE_STRIP);
    
    for coord in triangle:
        bgl.glVertex3f(*coord);    
    
    bgl.glVertex3f(*triangle[0]);
    
    bgl.glEnd();
        
    if(drawpoints):        
        bgl.glColor4f(*pointcolor);
        bgl.glPointSize(5.0);
        bgl.glBegin(bgl.GL_POINTS);
        
        for coord in triangle:
            bgl.glVertex3f(*coord);
            
        bgl.glEnd();
Пример #2
0
def drawLine(a,
             b,
             *,
             linethickness=5,
             linecolor=(1, 0, 0, 1),
             enable_depth=False):
    if (enable_depth):
        bgl.glEnable(bgl.GL_DEPTH_TEST)

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    bgl.glColor4f(*linecolor)
    bgl.glLineWidth(linethickness)
    bgl.glBegin(bgl.GL_LINE_STRIP)

    bgl.glVertex3f(*a)
    bgl.glVertex3f(*b)

    bgl.glEnd()

    if (enable_depth):
        bgl.glDisable(bgl.GL_DEPTH_TEST)
Пример #3
0
 def draw(self):
     width = render.getWindowWidth()
     height = render.getWindowHeight()
     
     # 2D Projection
     bgl.glMatrixMode(bgl.GL_PROJECTION)
     bgl.glLoadIdentity()
     bgl.glOrtho(0, width, height, 0, -1, 1)
     bgl.glMatrixMode(bgl.GL_MODELVIEW)
     bgl.glLoadIdentity()
     
     # 2D Shading
     bgl.glDisable(bgl.GL_CULL_FACE)
     bgl.glDisable(bgl.GL_LIGHTING)
     bgl.glDisable(bgl.GL_DEPTH_TEST)
     bgl.glShadeModel(bgl.GL_SMOOTH)
     
     # Line antialias
     bgl.glEnable(bgl.GL_LINE_SMOOTH)
     bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
     
     # 2D Blending (Alpha)
     bgl.glEnable(bgl.GL_BLEND)
     bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
     
     if len(self.controls.values()) <= 0: return
     
     ctrls = sorted(self.controls.values(), key=lambda x: x.zorder)
     for c in ctrls:
         c.draw()
Пример #4
0
    def draw(self):
        width = render.getWindowWidth()
        height = render.getWindowHeight()

        # 2D Projection
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadIdentity()
        bgl.glOrtho(0, width, height, 0, -1, 1)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glLoadIdentity()

        # 2D Shading
        bgl.glDisable(bgl.GL_CULL_FACE)
        bgl.glDisable(bgl.GL_LIGHTING)
        bgl.glDisable(bgl.GL_DEPTH_TEST)
        bgl.glShadeModel(bgl.GL_SMOOTH)

        # Line antialias
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

        # 2D Blending (Alpha)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        if len(self.controls.values()) <= 0: return

        ctrls = sorted(self.controls.values(), key=lambda x: x.zorder)
        for c in ctrls:
            c.draw()
Пример #5
0
    def draw_preview(self):
        bgl.glEnable(bgl.GL_MULTISAMPLE)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glDisable(bgl.GL_DEPTH_TEST)

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

        # add background gradient
        bgl.glBegin(bgl.GL_TRIANGLES)
        for i in range(0, 360, 10):
            r0, r1 = i * math.pi / 180.0, (i + 10) * math.pi / 180.0
            x0, y0 = math.cos(r0) * 2, math.sin(r0) * 2
            x1, y1 = math.cos(r1) * 2, math.sin(r1) * 2
            bgl.glColor4f(0, 0, 0.01, 0.0)
            bgl.glVertex2f(0, 0)
            bgl.glColor4f(0, 0, 0.01, 0.8)
            bgl.glVertex2f(x0, y0)
            bgl.glVertex2f(x1, y1)
        bgl.glEnd()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPopMatrix()
Пример #6
0
    def draw_spline_net(self):

        if not self.actions.r3d: return

        #print('drawing!')
        # if self.fps_low_warning: return     # skip drawing if low FPS warning is showing

        buf_matrix_target = self.polytrim_render.spline_network.xform.mx_p  # self.rftarget_draw.buf_matrix_model
        buf_matrix_target_inv = self.polytrim_render.spline_network.xform.imx_p  # self.rftarget_draw.buf_matrix_inverse
        buf_matrix_view = self.actions.r3d.view_matrix  # XForm.to_bglMatrix(self.actions.r3d.view_matrix)
        buf_matrix_view_invtrans = matrix_normal(
            self.actions.r3d.view_matrix
        )  # XForm.to_bglMatrix(matrix_normal(self.actions.r3d.view_matrix))
        buf_matrix_proj = self.actions.r3d.window_matrix  # XForm.to_bglMatrix(self.actions.r3d.window_matrix)
        view_forward = self.actions.r3d.view_rotation @ Vector((0, 0, -1))

        bgl.glEnable(bgl.GL_MULTISAMPLE)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        # bgl.glEnable(bgl.GL_POINT_SMOOTH)
        if True:  #why?
            alpha_above, alpha_below = 1.0, 0.1
            cull_backfaces = False
            alpha_backface = 0.2
            self.polytrim_render.draw(view_forward, 1.0, buf_matrix_target,
                                      buf_matrix_target_inv, buf_matrix_view,
                                      buf_matrix_view_invtrans,
                                      buf_matrix_proj, alpha_above,
                                      alpha_below, cull_backfaces,
                                      alpha_backface)
Пример #7
0
    def draw_callback(self, op, context):
        # Force Stop
        if self.is_handler_list_empty():
            self.unregister_handler()
            return

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        bgl.glEnable(bgl.GL_DEPTH_TEST)
        bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
        bgl.glPolygonOffset(1.0, 1.0)

        bgl.glColorMask(bgl.GL_FALSE, bgl.GL_FALSE, bgl.GL_FALSE, bgl.GL_FALSE)
        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_FILL)

        self.fill_batch.draw(self.fill_shader)

        bgl.glColorMask(bgl.GL_TRUE, bgl.GL_TRUE, bgl.GL_TRUE, bgl.GL_TRUE)
        bgl.glDisable(bgl.GL_POLYGON_OFFSET_FILL)

        bgl.glDepthMask(bgl.GL_FALSE)
        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_LINE)

        self.line_batch.draw(self.line_shader)

        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_FILL)
        bgl.glDepthMask(bgl.GL_TRUE)
        bgl.glDisable(bgl.GL_DEPTH_TEST)
Пример #8
0
def glSetDefaultOptions():
    bgl.glDisable(bgl.GL_LIGHTING)
    bgl.glEnable(bgl.GL_MULTISAMPLE)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
Пример #9
0
def glSetDefaultOptions(opts=None):
    bgl.glEnable(bgl.GL_MULTISAMPLE)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LIGHTING)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
Пример #10
0
def DrawGLLines(self, context, paths, temppaths, reflector_paths, reflected_temppaths, color, thickness, LINE_TYPE= "GL_LINE"):
    bgl.glEnable(bgl.GL_BLEND);
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA);
    bgl.glEnable(bgl.GL_LINE_SMOOTH);
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST);
#    bgl.glDisable(bgl.GL_DEPTH_TEST);

    bgl.glLineWidth(thickness);
    
    carr = context.scene.path_color;
    color = (carr[0],carr[1],carr[2],1.0);
    
    for path in paths:        
        bgl.glBegin(bgl.GL_LINE_STRIP);
        bgl.glColor4f(*color);
        
        for coord in path:
            bgl.glVertex3f(*coord);    
        
        bgl.glEnd();
    
    for path in reflector_paths:        
        bgl.glBegin(bgl.GL_LINE_STRIP);
        bgl.glColor4f(*color);
        
        for coord in path:
            bgl.glVertex3f(*coord);    
        
        bgl.glEnd();
    
    
    
    carr = context.scene.temp_path_color;
    color = (carr[0],carr[1],carr[2],1.0);
    for path in temppaths:
        bgl.glBegin(bgl.GL_LINE_STRIP);
        bgl.glColor4f(*color);
        
        for co in path:
            bgl.glVertex3f(*co);
            
        bgl.glEnd();
    
    
    for path in reflected_temppaths:
        bgl.glBegin(bgl.GL_LINE_STRIP);
        bgl.glColor4f(*color);
        
        for co in path:
            bgl.glVertex3f(*co);
            
        bgl.glEnd();

    # restore opengl defaults
    bgl.glLineWidth(1);
    bgl.glDisable(bgl.GL_BLEND);
#    bgl.glEnable(bgl.GL_DEPTH_TEST);
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #11
0
def draw_callback_nodeoutline(self, context):
    bgl.glLineWidth(1)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    # set color
    c1 = get_pref().draw_nodes.text_color1
    c2 = get_pref().draw_nodes.text_color2
    c3 = get_pref().draw_nodes.text_color3
    size = get_pref().draw_nodes.size
    white = (c1[0], c1[1], c1[2], self.alpha)
    green = (c2[0], c2[1], c2[2], self.alpha)
    red = (c3[0], c3[1], c3[2], self.alpha)

    list_node = context.space_data.edit_tree.nodes.get(
        context.window_manager.rsn_active_list)
    if not list_node: return

    node_list = [
        node for node in context.space_data.edit_tree.nodes
        if node in cache_executed_nodes
    ]
    try:
        for node in node_list:
            # draw time
            if node.id_data in cache_node_times:
                if node in cache_node_times[node.id_data]:
                    times = cache_node_times[node.id_data][node]
                    t = times[
                        'Execution'] if node.bl_idname != 'RenderNodeGroup' else times[
                            'Group']
                    t = t * 1000
                    if t < 0.1:
                        col = white
                    elif t < 1:
                        col = green
                    else:
                        col = red
                    draw_text_on_node(white,
                                      node.bl_label,
                                      node,
                                      size=size,
                                      corner_index=0,
                                      offset=(0, 3))
                    draw_text_on_node(col,
                                      f"{t:.2f}ms",
                                      node,
                                      size=size - 5,
                                      corner_index=0,
                                      offset=(0, size + 3))
    except:
        pass

    # restore
    #####################
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_SMOOTH)
Пример #12
0
    def draw_callback(self, op, context):
        if not self.is_visible():
            return
        # Force Stop
        wireframe_image = find_bpy_image_by_name(Config.coloring_texture_name)
        if self.is_handler_list_empty() or \
                not self._check_coloring_image(wireframe_image):
            self.unregister_handler()
            return

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        bgl.glEnable(bgl.GL_DEPTH_TEST)
        bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
        bgl.glPolygonOffset(1.0, 1.0)

        bgl.glColorMask(bgl.GL_FALSE, bgl.GL_FALSE, bgl.GL_FALSE, bgl.GL_FALSE)
        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_FILL)

        self.fill_batch.draw(self.fill_shader)

        bgl.glColorMask(bgl.GL_TRUE, bgl.GL_TRUE, bgl.GL_TRUE, bgl.GL_TRUE)
        bgl.glDisable(bgl.GL_POLYGON_OFFSET_FILL)

        bgl.glDepthMask(bgl.GL_FALSE)
        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_LINE)
        bgl.glEnable(bgl.GL_DEPTH_TEST)

        if not self._use_simple_shader:
            # coloring_image.bindcode should not be zero
            # if we don't want to destroy video driver in Blender
            if not wireframe_image or wireframe_image.bindcode == 0:
                self.switch_to_simple_shader()
            else:
                bgl.glActiveTexture(bgl.GL_TEXTURE0)
                bgl.glBindTexture(bgl.GL_TEXTURE_2D, wireframe_image.bindcode)
                self.line_shader.bind()
                self.line_shader.uniform_int('image', 0)
                self.line_shader.uniform_float('opacity', self._opacity)
                self.line_batch.draw(self.line_shader)

        if self._use_simple_shader:
            self.simple_line_shader.bind()
            self.simple_line_shader.uniform_float(
                'color', ((*self._colors[0][:3], self._opacity)))
            self.simple_line_batch.draw(self.simple_line_shader)

        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_FILL)
        bgl.glDepthMask(bgl.GL_TRUE)
        bgl.glDisable(bgl.GL_DEPTH_TEST)
def draw_image(face_data, opacity):
    bgl.glLineWidth(1)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    with gpu.matrix.push_pop():
        gpu.matrix.load_matrix(get_normalize_uvs_matrix())
        gpu.matrix.load_projection_matrix(Matrix.Identity(4))

        draw_background_colors(face_data, opacity)
        draw_lines(face_data)

    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_SMOOTH)
Пример #14
0
def draw_image(face_data, opacity):
    bgl.glLineWidth(1)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    with gpu.matrix.push_pop():
        gpu.matrix.load_matrix(get_normalize_uvs_matrix())
        gpu.matrix.load_projection_matrix(Matrix.Identity(4))

        draw_background_colors(face_data, opacity)
        draw_lines(face_data)

    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_SMOOTH)
Пример #15
0
def drawLine(a, b, linethickness, linecolor):
    
    bgl.glEnable(bgl.GL_BLEND);
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA);
    bgl.glEnable(bgl.GL_LINE_SMOOTH);
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST);
    
    bgl.glColor4f(*linecolor);
    bgl.glLineWidth(linethickness);
    bgl.glBegin(bgl.GL_LINE_STRIP);
    
    bgl.glVertex3f(*a);
    bgl.glVertex3f(*b);
    
    bgl.glEnd();
Пример #16
0
    def draw_callback(self, op, context):
        # Force Stop
        if self.is_handler_list_empty():
            self.unregister_handler()
            return

        if self.line_shader is None or self.line_batch is None:
            return

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        self.line_shader.bind()
        self.line_batch.draw(self.line_shader)
Пример #17
0
def drawTriangle(triangle,
                 linethickness,
                 linecolor,
                 fillcolor,
                 drawpoints=False,
                 pointcolor=None,
                 *,
                 enable_depth=False):
    if (enable_depth):
        bgl.glEnable(bgl.GL_DEPTH_TEST)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    #     for co in triangle:
    bgl.glColor4f(*fillcolor)
    bgl.glBegin(bgl.GL_TRIANGLES)

    for coord in triangle:
        bgl.glVertex3f(*coord)
    bgl.glEnd()

    bgl.glColor4f(*linecolor)
    bgl.glLineWidth(linethickness)
    bgl.glBegin(bgl.GL_LINE_STRIP)

    for coord in triangle:
        bgl.glVertex3f(*coord)

    bgl.glVertex3f(*triangle[0])

    bgl.glEnd()

    if (drawpoints):
        bgl.glColor4f(*pointcolor)
        bgl.glPointSize(5.0)
        bgl.glBegin(bgl.GL_POINTS)

        for coord in triangle:
            bgl.glVertex3f(*coord)

        bgl.glEnd()

    if (enable_depth):
        bgl.glDisable(bgl.GL_DEPTH_TEST)
Пример #18
0
    def draw_lines(self, context, obj, vertices, indices, topology=None):
        region = context.region
        region3d = context.region_data
        color = context.scene.DocProperties.decorations_colour

        fmt = GPUVertFormat()
        fmt.attr_add(id="pos", comp_type="F32", len=3, fetch_mode="FLOAT")
        if topology:
            fmt.attr_add(id="topo", comp_type="U8", len=1, fetch_mode="INT")

        vbo = GPUVertBuf(len=len(vertices), format=fmt)
        vbo.attr_fill(id="pos", data=vertices)
        if topology:
            vbo.attr_fill(id="topo", data=topology)

        ibo = GPUIndexBuf(type="LINES", seq=indices)

        batch = GPUBatch(type="LINES", buf=vbo, elem=ibo)

        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

        self.shader.bind()
        self.shader.uniform_float
        self.shader.uniform_float("viewMatrix", region3d.perspective_matrix)
        self.shader.uniform_float("winsize", (region.width, region.height))
        self.shader.uniform_float("color", color)

        # Horrific prototype code
        factor = self.camera_zoom_to_factor(
            context.space_data.region_3d.view_camera_zoom)
        camera_width_px = factor * context.region.width
        mm_to_px = camera_width_px / self.camera_width_mm
        # 0.00025 is a magic constant number I visually discovered to get the right number.
        # It probably should be dynamically calculated using system.dpi or something.
        viewport_drawing_scale = 0.00025 * mm_to_px
        self.shader.uniform_float("viewportDrawingScale",
                                  viewport_drawing_scale)

        batch.draw(self.shader)
Пример #19
0
def draw_func(self, context):

    if tinycad_dict['bevel'] and (len(tinycad_dict['bevel']) == 2):
        verts = tinycad_dict['bevel'][0]
        edges = tinycad_dict['bevel'][1]
    else:
        return

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

    # 3d lines
    bgl.glBegin(bgl.GL_LINES)
    for keys in edges:
        for k in keys:
            coordinate = verts[k]
            bgl.glVertex3f(*coordinate)
    bgl.glEnd()

    # 3d points
    vsize = 5
    bgl.glEnable(bgl.GL_POINT_SIZE)
    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glHint(bgl.GL_POINT_SMOOTH_HINT, bgl.GL_NICEST)
    bgl.glPointSize(vsize)    
    bgl.glColor3f(1.0, 0.6, 0.3)
    bgl.glBegin(bgl.GL_POINTS)
    for x, y, z in verts:
        bgl.glVertex3f(x, y, z)
    bgl.glEnd()    

    bgl.glDisable(bgl.GL_POINT_SIZE)
    bgl.glDisable(bgl.GL_POINT_SMOOTH)


    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #20
0
def draw_func(self, context):

    if tinycad_dict['bevel'] and (len(tinycad_dict['bevel']) == 2):
        verts = tinycad_dict['bevel'][0]
        edges = tinycad_dict['bevel'][1]
    else:
        return

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

    # 3d lines
    bgl.glBegin(bgl.GL_LINES)
    for keys in edges:
        for k in keys:
            coordinate = verts[k]
            bgl.glVertex3f(*coordinate)
    bgl.glEnd()

    # 3d points
    vsize = 5
    bgl.glEnable(bgl.GL_POINT_SIZE)
    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glHint(bgl.GL_POINT_SMOOTH_HINT, bgl.GL_NICEST)
    bgl.glPointSize(vsize)
    bgl.glColor3f(1.0, 0.6, 0.3)
    bgl.glBegin(bgl.GL_POINTS)
    for x, y, z in verts:
        bgl.glVertex3f(x, y, z)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_POINT_SIZE)
    bgl.glDisable(bgl.GL_POINT_SMOOTH)

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #21
0
    def draw_postview(self):
        buf_matrix_target = XForm(Matrix.Identity(4)).mx_p # self.rftarget_draw.buf_matrix_model
        buf_matrix_target_inv = XForm(Matrix.Identity(4)).imx_p # self.rftarget_draw.buf_matrix_inverse
        buf_matrix_view = self.actions.r3d.view_matrix # XForm.to_bglMatrix(self.actions.r3d.view_matrix)
        buf_matrix_view_invtrans = matrix_normal(self.actions.r3d.view_matrix) # XForm.to_bglMatrix(matrix_normal(self.actions.r3d.view_matrix))
        buf_matrix_proj = self.actions.r3d.window_matrix # XForm.to_bglMatrix(self.actions.r3d.window_matrix)
        view_forward = self.actions.r3d.view_rotation @ Vector((0,0,-1))

        bgl.glEnable(bgl.GL_MULTISAMPLE)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        # bgl.glEnable(bgl.GL_POINT_SMOOTH)
        if True:  #why?
            alpha_above,alpha_below = 1.0 , 0.1
            cull_backfaces = False
            alpha_backface = 0.01
            self.d3_points_render.draw(
                view_forward, 1.0,
                buf_matrix_target, buf_matrix_target_inv,
                buf_matrix_view, buf_matrix_view_invtrans, buf_matrix_proj,
                alpha_above, alpha_below, cull_backfaces, alpha_backface
            )
Пример #22
0
def draw_callback_3d(self, op, context):
    bgl.glPointSize(self.vertex_size)
    bgl.glLineWidth(self.edge_width)

    bgl.glEnable(bgl.GL_MULTISAMPLE)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

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

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

    bgl.glEnable(bgl.GL_DEPTH_TEST)
    bgl.glDepthFunc(bgl.GL_ALWAYS)

    self.shader.bind()
    if self.batch_path:
        self.batch_path.draw(self.shader)
    if self.batch_cp_faces:
        self.batch_cp_faces.draw(self.shader)
    if self.batch_cp_verts:
        self.batch_cp_verts.draw(self.shader)
def draw_geometry(n_id, options, data_vector, data_polygons, data_matrix,
                  data_edges):

    show_verts = options['show_verts']
    show_edges = options['show_edges']
    show_faces = options['show_faces']

    vertex_colors = options['vertex_colors']
    edge_colors = options['edge_colors']
    edge_width = options['edge_width']

    tran = options['transparent']
    shade = options['shading']

    verlen = options['verlen']
    max_verts_ = [len(d) for d in data_vector]

    if tran:
        polyholy = GL_POLYGON_STIPPLE
        edgeholy = GL_LINE_STIPPLE
        edgeline = GL_LINE_STRIP
    else:
        polyholy = GL_POLYGON
        edgeholy = GL_LINE
        edgeline = GL_LINES

    def get_max_k(i, verlen):
        k = i
        if i > verlen:
            k = verlen
        return k

    ''' vertices '''

    glEnable(GL_POINT_SIZE)
    glEnable(GL_POINT_SMOOTH)
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
    # glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST)

    vsize = options['vertex_size']

    if show_verts and data_vector:

        glPointSize(vsize)
        glColor3f(*vertex_colors)
        glBegin(GL_POINTS)

        for i, matrix in enumerate(data_matrix):
            k = get_max_k(i, verlen)
            for vert in data_vector[k]:
                vec = data_matrix[i] * vert
                glVertex3f(*vec)

        glEnd()

    glDisable(GL_POINT_SIZE)
    glDisable(GL_POINT_SMOOTH)
    ''' polygons '''

    if data_polygons and data_vector:
        num_datapolygon_lists = len(data_polygons)

        glEnable(polyholy)
        for i, matrix in enumerate(data_matrix):

            k = get_max_k(i, verlen)
            mesh_edges = set()
            if k >= num_datapolygon_lists:
                k = (num_datapolygon_lists - 1)
                #break

            if len(data_vector[k]) < 3:
                print("can't make faces between fewer than 3 vertices")
                continue

            for j, pol in enumerate(data_polygons[k]):

                if max(pol) >= max_verts_[k]:
                    continue

                if show_faces:
                    display_face(options, pol, data_vector, data_matrix, k, i)

                # collect raw edges, sort by index, use set to prevent dupes.
                if show_edges:
                    er = list(pol) + [pol[0]]
                    kb = {
                        tuple(sorted((e, er[i + 1])))
                        for i, e in enumerate(er[:-1])
                    }
                    mesh_edges.update(kb)

            if show_edges and mesh_edges:
                # glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
                glEnable(edgeholy)
                glLineWidth(edge_width)
                glColor3f(*edge_colors)
                glBegin(GL_LINES)
                for edge in mesh_edges:
                    for p in edge:
                        vec = data_matrix[i] * data_vector[k][p]
                        glVertex3f(*vec)

                glEnd()
                glDisable(edgeholy)

        glDisable(polyholy)
    ''' edges '''

    if data_edges and data_vector and show_edges:

        glColor3f(*edge_colors)
        glLineWidth(edge_width)
        # glEnable(GL_LINE_SMOOTH)
        glEnable(edgeholy)
        # glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)

        for i, matrix in enumerate(data_matrix):
            k = get_max_k(i, verlen)

            if k >= len(data_edges):
                continue

            if len(data_vector[k]) < 2:
                print("can't make edges between fewer than 2 vertices")
                continue

            for line in data_edges[k]:

                # i think this catches edges which refer to indices not present in
                # the accompanying vertex list.
                if max(line) >= max_verts_[k]:
                    continue

                glBegin(edgeline)
                for p in line:
                    vec = data_matrix[i] * data_vector[k][p]
                    glVertex3f(*vec)
                glEnd()

        glDisable(edgeholy)
        # glDisable(GL_LINE_SMOOTH)
    ''' matrix '''

    if data_matrix and not data_vector:
        md = MatrixDraw()
        for mat in data_matrix:
            md.draw_matrix(mat)
Пример #24
0
    def draw_postpixel(self):
        if not self.actions.r3d: return

        wtime, ctime = self.fps_time, time.time()
        self.frames += 1
        if ctime >= wtime + 1:
            self.fps = self.frames / (ctime - wtime)
            self.fps_list = self.fps_list[1:] + [self.fps]
            self.frames = 0
            self.fps_time = ctime

        if self.fps >= options['low fps threshold']: self.fps_low_start = ctime
        if ctime - self.fps_low_start > options['low fps time']:
            # exceeded allowed time for low fps
            if options['low fps warn'] and not hasattr(
                    self, 'fps_warning_shown_already'):
                self.fps_warning_shown_already = True
                self.show_lowfps_warning()

        bgl.glEnable(bgl.GL_MULTISAMPLE)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)

        try:
            rgn = self.actions.region
            sw, sh = rgn.width, rgn.height
            m = self.drawing.get_dpi_mult()

            if options['visualize counts']:
                count_str = 'v:%d  e:%d  f:%d' % self.get_target_geometry_counts(
                )
                tw = self.drawing.get_text_width(count_str)
                th = self.drawing.get_text_height(count_str)
                self.drawing.text_draw2D(count_str,
                                         Point2D((sw - tw - 10, th + 10)),
                                         (1, 1, 1, 0.25),
                                         dropshadow=(0, 0, 0, 0.5),
                                         fontsize=12)

            if options['visualize fps'] and self.actions.region:
                bgl.glEnable(bgl.GL_BLEND)
                pr = profiler.start('fps postpixel')

                lw, lh = len(self.fps_list), 60

                def p(x, y):
                    return (sw - 10 + (-lw + x) * m, 30 + y * m)

                def v(x, y):
                    bgl.glVertex2f(*p(x, y))

                bgl.glBegin(bgl.GL_QUADS)
                bgl.glColor4f(0, 0, 0, 0.2)
                v(0, 0)
                v(lw, 0)
                v(lw, lh)
                v(0, lh)
                bgl.glEnd()

                bgl.glBegin(bgl.GL_LINES)
                bgl.glColor4f(0.2, 0.2, 0.2, 0.3)
                for i in [10, 20, 30, 40, 50]:
                    v(0, i)
                    v(lw, i)
                bgl.glEnd()

                if options['low fps warn']:
                    fw = options['low fps time']
                    fh = options['low fps threshold']
                    bgl.glBegin(bgl.GL_QUADS)
                    bgl.glColor4f(0.5, 0.1, 0.1, 0.3)
                    v(lw - fw, 0)
                    v(lw, 0)
                    v(lw, fh)
                    v(lw - fw, fh)
                    bgl.glEnd()

                bgl.glBegin(bgl.GL_LINE_STRIP)
                bgl.glColor4f(0.1, 0.8, 1.0, 0.3)
                for i in range(lw):
                    v(i, min(lh, self.fps_list[i]))
                bgl.glEnd()

                bgl.glBegin(bgl.GL_LINE_STRIP)
                bgl.glColor4f(0, 0, 0, 0.5)
                v(0, 0)
                v(lw, 0)
                v(lw, lh)
                v(0, lh)
                v(0, 0)
                bgl.glEnd()

                self.drawing.text_draw2D('%2.2f' % self.fps,
                                         Point2D(p(2, lh - 2)), (1, 1, 1, 0.5),
                                         fontsize=12)
                pr.done()

            if not self.draw_ui:
                k = next(iter(default_rf_keymaps['toggle ui']))
                self.drawing.text_draw2D('Press %s to show UI' % k,
                                         Point2D((10, sh - 10)),
                                         (1, 1, 1, 0.25),
                                         fontsize=12)

            pr = profiler.start('tool draw postpixel')
            self.tool.draw_postpixel()
            pr.done()

            pr = profiler.start('widget draw postpixel')
            self.rfwidget.draw_postpixel()
            pr.done()

            pr = profiler.start('window manager draw postpixel')
            self.window_debug_fps.set_label('FPS: %0.2f' % self.fps)
            self.window_debug_save.set_label(
                'Time: %0.0f' % (self.time_to_save or float('inf')))
            self.window_manager.draw_postpixel(self.actions.context)
            pr.done()

        except AssertionError as e:
            message, h = debugger.get_exception_info_and_hash()
            print(message)
            message = '\n'.join('- %s' % l for l in message.splitlines())
            self.alert_user(message=message, level='assert', msghash=h)
        except Exception as e:
            message, h = debugger.get_exception_info_and_hash()
            print(message)
            message = '\n'.join('- %s' % l for l in message.splitlines())
            self.alert_user(message=message, level='exception', msghash=h)
Пример #25
0
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 = internals.qcd_slots.get_name(f"{slot_num}")
        if qcd_slot_name:
            qcd_laycol = internals.layer_collections[qcd_slot_name]["ptr"]
            collection_objects = qcd_laycol.collection.objects
            selected_objects = get_move_selection()
            active_object = 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 internals.qcd_slots.contains(idx=f"{num+2}"):
                    tr = rounding

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

                if not internals.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 = internals.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()
Пример #26
0
def draw_rounded_rect(area,
                      shader,
                      color,
                      tl=5,
                      tr=5,
                      bl=5,
                      br=5,
                      outline=False):
    sides = 32

    tl = round(tl * scale_factor())
    tr = round(tr * scale_factor())
    bl = round(bl * scale_factor())
    br = round(br * scale_factor())

    bgl.glEnable(bgl.GL_BLEND)

    if outline:
        thickness = round(2 * scale_factor())
        thickness = max(thickness, 2)

        bgl.glLineWidth(thickness)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    draw_type = 'TRI_FAN' if not outline else 'LINE_STRIP'

    # top left corner
    vert_x = area["vert"][0] + tl
    vert_y = area["vert"][1] - tl
    tl_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (8 <= side <= 16):
            cosine = tl * cos(side * 2 * pi / sides) + vert_x
            sine = tl * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    # top right corner
    vert_x = area["vert"][0] + area["width"] - tr
    vert_y = area["vert"][1] - tr
    tr_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (0 <= side <= 8):
            cosine = tr * cos(side * 2 * pi / sides) + vert_x
            sine = tr * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    # bottom left corner
    vert_x = area["vert"][0] + bl
    vert_y = area["vert"][1] - area["height"] + bl
    bl_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (16 <= side <= 24):
            cosine = bl * cos(side * 2 * pi / sides) + vert_x
            sine = bl * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    # bottom right corner
    vert_x = area["vert"][0] + area["width"] - br
    vert_y = area["vert"][1] - area["height"] + br
    br_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (24 <= side <= 32):
            cosine = br * cos(side * 2 * pi / sides) + vert_x
            sine = br * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    if not outline:
        vertices = []
        indices = []
        base_ind = 0

        # left edge
        width = max(tl, bl)
        le_x = tl_vert[0] - tl
        vertices.extend([(le_x, tl_vert[1]), (le_x + width, tl_vert[1]),
                         (le_x, bl_vert[1]), (le_x + width, bl_vert[1])])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # right edge
        width = max(tr, br)
        re_x = tr_vert[0] + tr
        vertices.extend([(re_x, tr_vert[1]), (re_x - width, tr_vert[1]),
                         (re_x, br_vert[1]), (re_x - width, br_vert[1])])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # top edge
        width = max(tl, tr)
        te_y = tl_vert[1] + tl
        vertices.extend([(tl_vert[0], te_y), (tl_vert[0], te_y - width),
                         (tr_vert[0], te_y), (tr_vert[0], te_y - width)])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # bottom edge
        width = max(bl, br)
        be_y = bl_vert[1] - bl
        vertices.extend([(bl_vert[0], be_y), (bl_vert[0], be_y + width),
                         (br_vert[0], be_y), (br_vert[0], be_y + width)])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # middle
        vertices.extend([tl_vert, tr_vert, bl_vert, br_vert])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])

        batch = batch_for_shader(shader,
                                 'TRIS', {"pos": vertices},
                                 indices=indices)

        shader.uniform_float("color", color)
        batch.draw(shader)

    else:
        overlap = round(thickness / 2 - scale_factor() / 2)

        # left edge
        le_x = tl_vert[0] - tl
        vertices = [(le_x, tl_vert[1] + (overlap if tl == 0 else 0)),
                    (le_x, bl_vert[1] - (overlap if bl == 0 else 0))]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        # right edge
        re_x = tr_vert[0] + tr
        vertices = [(re_x, tr_vert[1] + (overlap if tr == 0 else 0)),
                    (re_x, br_vert[1] - (overlap if br == 0 else 0))]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        # top edge
        te_y = tl_vert[1] + tl
        vertices = [(tl_vert[0] - (overlap if tl == 0 else 0), te_y),
                    (tr_vert[0] + (overlap if tr == 0 else 0), te_y)]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        # bottom edge
        be_y = bl_vert[1] - bl
        vertices = [(bl_vert[0] - (overlap if bl == 0 else 0), be_y),
                    (br_vert[0] + (overlap if br == 0 else 0), be_y)]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        bgl.glDisable(bgl.GL_LINE_SMOOTH)

    bgl.glDisable(bgl.GL_BLEND)
Пример #27
0
def draw_geometry(n_id, options, data_vector, data_polygons, data_matrix, data_edges):

    show_verts = options['show_verts']
    show_edges = options['show_edges']
    show_faces = options['show_faces']

    vertex_colors = options['vertex_colors']
    edge_colors = options['edge_colors']
    edge_width = options['edge_width']

    tran = options['transparent']
    shade = options['shading']

    verlen = options['verlen']
    max_verts_ = [len(d) for d in data_vector]

    if tran:
        polyholy = GL_POLYGON_STIPPLE
        edgeholy = GL_LINE_STIPPLE
        edgeline = GL_LINE_STRIP
    else:
        polyholy = GL_POLYGON
        edgeholy = GL_LINE
        edgeline = GL_LINES

    def get_max_k(i, verlen):
        k = i
        if i > verlen:
            k = verlen
        return k

    ''' vertices '''

    glEnable(GL_POINT_SIZE)
    glEnable(GL_POINT_SMOOTH)
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
    # glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST)

    vsize = options['vertex_size']

    if show_verts and data_vector:

        glPointSize(vsize)
        glColor3f(*vertex_colors)
        glBegin(GL_POINTS)

        for i, matrix in enumerate(data_matrix):
            k = get_max_k(i, verlen)
            for vert in data_vector[k]:
                vec = data_matrix[i] * vert
                glVertex3f(*vec)

        glEnd()

    glDisable(GL_POINT_SIZE)
    glDisable(GL_POINT_SMOOTH)

    ''' polygons '''

    if data_polygons and data_vector:
        num_datapolygon_lists = len(data_polygons)

        glEnable(polyholy)
        for i, matrix in enumerate(data_matrix):

            k = get_max_k(i, verlen)
            mesh_edges = set()
            if k >= num_datapolygon_lists:
                k = (num_datapolygon_lists-1)
                #break

            for j, pol in enumerate(data_polygons[k]):

                if max(pol) >= max_verts_[k]:
                    continue

                if show_faces:
                    display_face(options, pol, data_vector, data_matrix, k, i)

                # collect raw edges, sort by index, use set to prevent dupes.
                if show_edges:
                    er = list(pol) + [pol[0]]
                    kb = {tuple(sorted((e, er[i+1]))) for i, e in enumerate(er[:-1])}
                    mesh_edges.update(kb)

            if show_edges and mesh_edges:
                # glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
                glEnable(edgeholy)
                glLineWidth(edge_width)
                glColor3f(*edge_colors)
                glBegin(GL_LINES)
                for edge in mesh_edges:
                    for p in edge:
                        vec = data_matrix[i] * data_vector[k][p]
                        glVertex3f(*vec)

                glEnd()
                glDisable(edgeholy)

        glDisable(polyholy)

    ''' edges '''

    if data_edges and data_vector and show_edges:

        glColor3f(*edge_colors)
        glLineWidth(edge_width)
        glEnable(edgeholy)

        for i, matrix in enumerate(data_matrix):
            k = get_max_k(i, verlen)

            if k >= len(data_edges):
                continue

            for line in data_edges[k]:

                # i think this catches edges which refer to indices not present in
                # the accompanying vertex list.
                if max(line) >= max_verts_[k]:
                    continue

                glBegin(edgeline)
                for p in line:
                    vec = data_matrix[i] * data_vector[k][p]
                    glVertex3f(*vec)
                glEnd()

        glDisable(edgeholy)

    ''' matrix '''

    if data_matrix and not data_vector:
        md = MatrixDraw()
        for mat in data_matrix:
            md.draw_matrix(mat)
Пример #28
0
    def draw_postview(self):
        if not self.actions.r3d: return
        if self.fps_low_warning:
            return  # skip drawing if low FPS warning is showing

        buf_matrix_target = self.rftarget_draw.buf_matrix_model
        buf_matrix_target_inv = self.rftarget_draw.buf_matrix_inverse
        buf_matrix_view = XForm.to_bglMatrix(self.actions.r3d.view_matrix)
        buf_matrix_view_invtrans = XForm.to_bglMatrix(
            matrix_normal(self.actions.r3d.view_matrix))
        buf_matrix_proj = XForm.to_bglMatrix(self.actions.r3d.window_matrix)
        view_forward = self.actions.r3d.view_rotation * Vector((0, 0, -1))

        bgl.glEnable(bgl.GL_MULTISAMPLE)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)

        # get frame of target, used for symmetry decorations on sources
        ft = self.rftarget.get_frame()

        if options['symmetry view'] != 'None' and self.rftarget.symmetry:
            pr = profiler.start('render sources')
            for rs, rfs in zip(self.rfsources, self.rfsources_draw):
                rfs.draw(view_forward,
                         buf_matrix_target,
                         buf_matrix_target_inv,
                         buf_matrix_view,
                         buf_matrix_view_invtrans,
                         buf_matrix_proj,
                         1.00,
                         0.05,
                         False,
                         0.5,
                         symmetry=self.rftarget.symmetry,
                         symmetry_view=options['symmetry view'],
                         symmetry_effect=options['symmetry effect'],
                         symmetry_frame=ft)
            pr.done()

        pr = profiler.start('render target')
        alpha_above, alpha_below = options['target alpha'], options[
            'target hidden alpha']
        cull_backfaces = options['target cull backfaces']
        alpha_backface = options['target alpha backface']
        self.rftarget_draw.draw(view_forward, buf_matrix_target,
                                buf_matrix_target_inv, buf_matrix_view,
                                buf_matrix_view_invtrans, buf_matrix_proj,
                                alpha_above, alpha_below, cull_backfaces,
                                alpha_backface)
        pr.done()

        pr = profiler.start('grease marks')
        bgl.glBegin(bgl.GL_QUADS)
        for stroke_data in self.grease_marks:
            bgl.glColor4f(*stroke_data['color'])
            t = stroke_data['thickness']
            s0, p0, n0, d0, d1 = None, None, None, None, None
            for s1 in stroke_data['marks']:
                p1, n1 = s1
                if p0 and p1:
                    v01 = p1 - p0
                    if d0 is None: d0 = Direction(v01.cross(n0))
                    d1 = Direction(v01.cross(n1))
                    bgl.glVertex3f(*(p0 - d0 * t + n0 * 0.001))
                    bgl.glVertex3f(*(p0 + d0 * t + n0 * 0.001))
                    bgl.glVertex3f(*(p1 + d1 * t + n1 * 0.001))
                    bgl.glVertex3f(*(p1 - d1 * t + n1 * 0.001))
                s0, p0, n0, d0 = s1, p1, n1, d1
        bgl.glEnd()
        pr.done()

        pr = profiler.start('render other')
        self.tool.draw_postview()
        self.rfwidget.draw_postview()
        pr.done()
Пример #29
0
def draw_callback_abc(self, context):
    def draw_letter(x=10, y=10, letter="-"):
        bgl.glColor3f(0.1, 0.1, 0.1)
        blf.position(0, x - 7, y - 7, 0)
        blf.size(0, 18, 72)
        blf.draw(0, letter)

    def draw_point(x=10, y=10, size=4, color=(0.5, 0.5, 0.5)):
        bgl.glPointSize(size)
        bgl.glColor3f(color[0], color[1], color[2])
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex2i(x, y)
        bgl.glEnd()

    def draw_line(start, end, color=(0.9, 0.9, 0.9)):
        # outer
        bgl.glLineWidth(4)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor3f(0.1, 0.1, 0.1)
        bgl.glVertex2i(start[0], start[1])
        bgl.glVertex2i(end[0], end[1])
        bgl.glEnd()

        # inner
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor3f(color[0], color[1], color[2])
        bgl.glVertex2i(start[0], start[1])
        bgl.glVertex2i(end[0], end[1])
        bgl.glEnd()

    font_id = 0

    base_dupli_offset = next((group.dupli_offset
                              for group in self.sp_obj.users_group
                              if group.OAGroup.oa_type in ('BASE', 'SIMP')))
    impl_dupli_offset = context.object.users_group[
        self.group_index].dupli_offset
    oa_type = context.object.users_group[self.group_index].OAGroup.oa_type

    scene = context.scene
    region = context.region
    rv3d = context.region_data

    sp_obj_matrix_world = self.sp_obj.matrix_world

    for sp_idx in range(len(self.snap_points)):
        if not self.show_all_sp:
            if self.index != sp_idx:
                continue

        a = self.sp_obj.data.vertices[self.snap_points[sp_idx].a].co
        b = self.sp_obj.data.vertices[self.snap_points[sp_idx].b].co
        c = self.sp_obj.data.vertices[self.snap_points[sp_idx].c].co

        factor = 1.5
        a_norm = c - (c - a).normalized() / factor
        b_norm = c - (c - b).normalized() / factor
        c_norm = c

        a_3d = (sp_obj_matrix_world * a_norm)
        b_3d = (sp_obj_matrix_world * b_norm)
        c_3d = (sp_obj_matrix_world * c_norm)

        if oa_type == 'IMPL':
            offset = (impl_dupli_offset - base_dupli_offset)
            a_3d += offset
            b_3d += offset
            c_3d += offset

        a_3d_to_region_2d = view3d_utils.location_3d_to_region_2d(
            region, rv3d, a_3d)
        b_3d_to_region_2d = view3d_utils.location_3d_to_region_2d(
            region, rv3d, b_3d)
        c_3d_to_region_2d = view3d_utils.location_3d_to_region_2d(
            region, rv3d, c_3d)

        # abort when viewport is to close or outside the 3d-view because location_3d_to_region_2d() returns None
        if not all((a_3d_to_region_2d, b_3d_to_region_2d, c_3d_to_region_2d)):
            return

        a_2d = tuple(map(ceil, a_3d_to_region_2d))
        b_2d = tuple(map(ceil, b_3d_to_region_2d))
        c_2d = tuple(map(ceil, c_3d_to_region_2d))

        # draw triangle
        # filled
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POLYGON)
        bgl.glColor4f(0.8, 0.5, 0.5, 0.2)
        for x, y in (a_2d, b_2d, c_2d):
            bgl.glVertex2i(x, y)
        bgl.glEnd()
        bgl.glDisable(bgl.GL_BLEND)

        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_POLYGON_SMOOTH_HINT, bgl.GL_NICEST)

        # outer
        bgl.glLineWidth(3)
        bgl.glBegin(bgl.GL_LINE_LOOP)
        bgl.glColor3f(0.1, 0.1, 0.1)
        for x, y in (a_2d, b_2d, c_2d):
            bgl.glVertex2i(x, y)
        bgl.glEnd()
        # inner
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_LOOP)
        bgl.glColor3f(0.9, 0.9, 0.9)
        for x, y in (a_2d, b_2d, c_2d):
            bgl.glVertex2i(x, y)
        bgl.glEnd()

        bgl.glDisable(bgl.GL_LINE_SMOOTH)

        # abc-points/letters
        # black background
        for x, y in (a_2d, b_2d, c_2d):
            draw_point(x, y, 20, (0, 0, 0))

        # white background
        for x, y in (a_2d, b_2d, c_2d):
            draw_point(x, y, 18, (1, 1, 1))

        #draw_point(a_2d[0], a_2d[1], 4, (0.9, 0.1, 0.1))
        draw_letter(a_2d[0], a_2d[1], 'A')

        # draw_point(b_2d[0], b_2d[1], 4, (0.1, 0.9, 0.1))
        draw_letter(b_2d[0], b_2d[1], 'B')

        # draw_point(c_2d[0], c_2d[1], 4, (0.3, 0.3, 0.9))
        draw_letter(c_2d[0], c_2d[1], 'C')

        # normal-line
        normal_start_3d = (a_3d + b_3d + c_3d) / 3
        normal_end_3d = normal_start_3d + (c_3d - a_3d).cross(
            c_3d - b_3d)  # /1.5 # scale normal

        normal_start_2d = tuple(
            map(
                ceil,
                view3d_utils.location_3d_to_region_2d(region, rv3d,
                                                      normal_start_3d)))
        normal_end_2d = tuple(
            map(
                ceil,
                view3d_utils.location_3d_to_region_2d(region, rv3d,
                                                      normal_end_3d)))

        draw_line(normal_start_2d, normal_end_2d)

        if context.scene.OAEditorSettings.draw_sp_idx:
            # sp-index
            sp_idx_2d = (
                int((a_2d[0] + b_2d[0]) / 2),
                a_2d[1] + b_2d[1] - normal_start_2d[1]
            )  # is short for ((a_2d[1] + b_2d[1])/2) + ((a_2d[1] + b_2d[1])/2) - normal_start_2d[1],
            # black background
            draw_point(sp_idx_2d[0], sp_idx_2d[1], 20, (0, 0, 0))
            # white background
            draw_point(sp_idx_2d[0], sp_idx_2d[1], 18, (1, 1, 1))
            draw_letter(sp_idx_2d[0], sp_idx_2d[1], str(sp_idx))

    # restore opengl defaults
    bgl.glPointSize(1)
    bgl.glLineWidth(1)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #30
0
def draw_callback_nodeoutline(self, context):
    if context.window_manager.rsn_node_list == '':
        pass

    bgl.glLineWidth(1)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

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

    # draw outline
    ########################

    # set color
    task_outer = (self.task_color[0], self.task_color[1], self.task_color[2],
                  self.alpha)
    file_path_outer = (self.file_path_color[0], self.file_path_color[1],
                       self.file_path_color[2], self.alpha)

    col_outer = (self.settings_color[0], self.settings_color[1],
                 self.settings_color[2], self.alpha)
    col_inner = (0.0, 0.0, 0.0, self.alpha + 0.1)

    node_list = context.window_manager.rsn_node_list.split(',')

    # draw all nodes
    for node_name in node_list:
        try:
            node = context.space_data.edit_tree.nodes[node_name]
            if node.bl_idname == 'RSNodeTaskNode':
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius * 1.25,
                                         colour=task_outer)
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius * 1.25 - 1.25,
                                         colour=col_inner)
            elif node.bl_idname in {
                    'RenderNodeSceneFilePath', 'RSNodeFilePathInputNode'
            }:
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius,
                                         colour=file_path_outer)
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius - 1,
                                         colour=col_inner)
            elif node.bl_idname != 'NodeReroute':
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius,
                                         colour=col_outer)
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius - 1,
                                         colour=col_inner)
        except KeyError:
            pass

    # draw text
    ##################
    if self.show_text_info:
        # properties text
        task_text = "No Active Task!" if context.window_manager.rsn_viewer_node == '' else context.window_manager.rsn_viewer_node
        camera = context.scene.camera.name if context.scene.camera else "No Scene camera"
        is_save = True if bpy.data.filepath != '' else False
        file_path_text = context.scene.render.filepath if is_save else "Save your file first!"

        texts = [
            f"Task: {task_text}",
            f"Camera: {camera}",
            f"Engine: {context.scene.render.engine}",
            f"Frame: {context.scene.frame_start} - {context.scene.frame_end}",
            f"FilePath: {file_path_text}",
        ]

        # text background
        r, g, b = self.background_color
        longest_text = max(texts, key=len, default='')
        size = blf.dimensions(0, longest_text)  # get the longest text
        size = [v * 1.5 / context.preferences.view.ui_scale
                for v in size]  # scale with the ui scale

        # set corner
        top = 125
        bottom = 25
        step = 25

        vertices = [
            (10 + size[0], top + size[1]),
            (20, top + size[1]),
            (20, 25),
            (10 + size[0], bottom),
        ]

        draw_round_rectangle(shader,
                             vertices,
                             radius=18,
                             colour=(0, 0, 0, self.alpha))  # shadow
        draw_round_rectangle(shader,
                             vertices,
                             radius=14,
                             colour=(r, g, b, self.alpha))  # main box

        # draw texts
        r, g, b = self.text_color
        size = 20

        for i, text in enumerate(texts):
            draw_text_2d((r, g, b, self.alpha, size), text, 20, top - step * i)

    # restore
    #####################
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_SMOOTH)