def draw_lines(vertices, indices, color): bgl.glEnable(bgl.GL_BLEND) shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos": vertices}, indices=indices) shader.bind() shader.uniform_float("color", color) batch.draw(shader)
def draw_gems(self, context, ratio_w=1, ratio_h=1): from_scene_scale = unit.Scale(context).from_scene view_normal = Vector((0.0, 0.0, 1.0)) @ self.region_3d.view_matrix angle_thold = pi / 1.8 fontid = 0 blf.size(fontid, self.prefs.view_font_size_gem_size, 72) blf.color(fontid, 0.0, 0.0, 0.0, 1.0) shader = gpu.shader.from_builtin("2D_UNIFORM_COLOR") depsgraph = context.depsgraph 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 shader.bind() 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)) for stone, cut, size, size_fmt, color in self.gems_raw: if ob_stone == stone and ob_cut == cut and ob_size == size: shader.uniform_float("color", color) break me = ob.to_mesh(depsgraph, True) me.transform(dup.matrix_world) verts = me.vertices 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) bpy.data.meshes.remove(me) # Size # ----------------------------- ob_loc = dup.matrix_world.translation.to_tuple() loc_x, loc_y = loc_3d_to_2d(self.region, self.region_3d, ob_loc, 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)
def draw_line(v1, v2, rgba): coords = [(v1[0], v1[1]), (v2[0], v2[1])] batch = batch_for_shader(shader, 'LINES', {"pos": coords}) # noinspection PyBroadException try: if v1 is not None and v2 is not None: shader.bind() shader.uniform_float("color", rgba) batch.draw(shader) except: pass
def draw_callback(op): startpos = op.mouse_cur endpos = op.center coords = [startpos.to_tuple(), endpos.to_tuple()] batch = batch_for_shader(shader, 'LINES', {"pos": coords}) try: shader.bind() shader.uniform_float("color", op.line_color) batch.draw(shader) except: pass
def draw_line2d(x1, y1, x2, y2, width, color): coords = ( (x1, y1), (x2, y2)) indices = ( (0, 1),) bgl.glEnable(bgl.GL_BLEND) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos": coords}, indices=indices) shader.bind() shader.uniform_float("color", color) batch.draw(shader)
def draw_lines(face_data): coords = [] for uvs, _ in face_data: for i in range(len(uvs)): start = uvs[i] end = uvs[(i+1) % len(uvs)] coords.append((start[0], start[1])) coords.append((end[0], end[1])) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos" : coords}) shader.bind() shader.uniform_float("color", (0, 0, 0, 1)) batch.draw(shader)
def draw_background_colors(face_data, opacity): coords = [uv for uvs, _ in face_data for uv in uvs] colors = [(*color, opacity) for uvs, color in face_data for _ in range(len(uvs))] indices = [] offset = 0 for uvs, _ in face_data: triangles = tessellate_uvs(uvs) indices.extend([index + offset for index in triangle] for triangle in triangles) offset += len(uvs) shader = gpu.shader.from_builtin('2D_FLAT_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos" : coords, "color" : colors}, indices=indices) batch.draw(shader)
def draw_rect(x, y, width, height, color): xmax = x + width ymax = y + height points = [[x, y], # [x, y] [x, ymax], # [x, y] [xmax, ymax], # [x, y] [xmax, y], # [x, y] ] indices = ((0, 1, 2), (2, 3, 0)) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos": points}, indices=indices) shader.bind() shader.uniform_float("color", color) bgl.glEnable(bgl.GL_BLEND) batch.draw(shader)
def draw(self, context): width = self.region.width height = self.region.height x = self.view_padding_left y = height - self.view_padding_top # Gem map # ----------------------------- if not self.use_navigate: bgl.glEnable(bgl.GL_BLEND) bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.offscreen.color_texture) shader_img.bind() shader_img.uniform_int("image", 0) args = { "pos": self.rect_coords(0, 0, width, height), "texCoord": self.rect_coords(0, 0, 1, 1), } batch = batch_for_shader(shader_img, "TRI_FAN", args) batch.draw(shader_img) # Onscreen text # ----------------------------- y = self.onscreen_gem_table(x, y) y -= self.view_margin if self.show_warn: y = self.onscreen_warning(x, y) y -= self.view_margin self.onscreen_options(x, y) # Restore OpenGL defaults # ---------------------------- bgl.glDisable(bgl.GL_BLEND)
def draw_image(x, y, width, height, image, transparency, crop=(0, 0, 1, 1)): # draw_rect(x,y, width, height, (.5,0,0,.5)) coords = [ (x, y), (x + width, y), (x, y + height), (x + width, y + height)] uvs = [(crop[0], crop[1]), (crop[2], crop[1]), (crop[0], crop[3]), (crop[2], crop[3]), ] indices = [(0, 1, 2), (2, 1, 3)] shader = gpu.shader.from_builtin('2D_IMAGE') batch = batch_for_shader(shader, 'TRIS', {"pos": coords, "texCoord": uvs}, indices=indices) # send image to gpu if it isn't there already if image.gl_load(): raise Exception() # texture identifier on gpu texture_id = image.bindcode # in case someone disabled it before bgl.glEnable(bgl.GL_BLEND) # bind texture to image unit 0 bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture_id) shader.bind() # tell shader to use the image that is bound to image unit 0 shader.uniform_int("image", 0) batch.draw(shader) bgl.glDisable(bgl.GL_TEXTURE_2D)
def draw_callback_px(): """Draw on the viewports""" ctx = bpy.context vcn = ctx.scene.channel_names if not vcn.enable_names: return () glEnable(GL_BLEND) # enable transparency region = ctx.region xwin1, ywin1 = region.view2d.region_to_view(0, 0) xwin2, ywin2 = region.view2d.region_to_view(region.width, region.height) x = 22 # x position/offset f_size = (32 - (ywin2 - ywin1) ) * 0.1 # scale font DPI according to sequencer zoom level dpi = int(72 * (f_size + 1)) # BG width = 100 + (50 * f_size) # width + scaling depending on zoom level vertices = ((15, 15), (width, 15), (15, region.height), (width, region.height)) indices = ((0, 1, 2), (2, 1, 3)) VCN_BG_shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') VCN_batch = batch_for_shader(VCN_BG_shader, 'TRIS', {"pos": vertices}, indices=indices) VCN_BG_shader.bind() VCN_BG_shader.uniform_float("color", (0.0, 0.0, 0.0, 0.8)) VCN_batch.draw(VCN_BG_shader) # TEXT blf.size(0, 10, dpi) for item in vcn.list: y = item.item.channel pos_x, pos_y = region.view2d.view_to_region(x, y, clip=False) blf.position(0, x, pos_y + 10, 0) blf.color(0, 1, 1, 1, 1) blf.draw(0, item.name) glDisable(GL_BLEND)
def draw_callback_2d(self, context): font_id = 0 # XXX, need to find out how best to get this. # Draw text to indicate that draw mode is active region = context.region text = "- Mesh Paint Mode -" # subtext = "LMB - Add Model | G - Move, R - Rotate, MOUSEWHEEL 0.1, 0.01 (shift) - Scale | RMB / ESC - Cancel" xt = int(region.width / 2.0) blf.size(font_id, 24, 72) blf.position(0, xt - blf.dimensions(0, text)[0] / 2, 60, 0) blf.draw(0, text) # blf.size(font_id, 20, 72) # blf.position(1, xt - blf.dimensions(0, subtext)[0] / 2, 30 , 1) # blf.draw(1, subtext) if self.transform_mode == "ROTATE": line = [] line.append((self.model_2d_point.x, self.model_2d_point.y)) line.append((self.mouse_coord.x, self.mouse_coord.y)) shader = gpu.shader.from_builtin("2D_UNIFORM_COLOR") bgl.glEnable(bgl.GL_BLEND) bgl.glLineWidth(2) batch = batch_for_shader(shader, "LINE_STRIP", {"pos": line}) shader.bind() shader.uniform_float("color", (1.0, 1.0, 0.0, 1.0)) batch.draw(shader) text_angle = "{}".format(round(self.rotate_angle, 2)) blf.size(font_id, 20, 72) blf.position(2, line[0][0], line[0][1] + 100, 1) blf.draw(2, text_angle) # restore opengl defaults bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND)
def draw(uuid): bgl.glEnable(bgl.GL_PROGRAM_POINT_SIZE) pm = bpy.context.region_data.perspective_matrix ci = PCVManager.cache[uuid] if (not bobjects.get(ci['name'])): ci['kill'] = True cls.gc() return if (not ci['draw']): cls.gc() return shader = ci['shader'] batch = ci['batch'] if (ci['current_display_percent'] != ci['display_percent']): l = ci['display_percent'] ci['current_display_percent'] = l vs = ci['vertices'] cs = ci['colors'] batch = batch_for_shader(shader, 'POINTS', { "position": vs[:l], "color": cs[:l], }) ci['batch'] = batch o = ci['object'] pcv = o.point_cloud_visualizer shader.bind() shader.uniform_float("perspective_matrix", pm) shader.uniform_float("object_matrix", o.matrix_world) shader.uniform_float("point_size", pcv.point_size) shader.uniform_float("alpha_radius", pcv.alpha_radius) batch.draw(shader) ci['drawing'] = True
def draw(self, uniforms, space_3d): """Dispatches drawing for the buffer by creating and drawing batch. :param uniforms: list of uniforms tuples to be sent to shader :type uniforms: collections.Iterable[(str, type, bytearray, int, int)] :param space_3d: space 3D data of viewport to which buffers should be drawn :type space_3d: bpy.types.SpaceView3D """ # nothing to draw really if not self.has_entries(): return # triangles are not drawn into wireframe views if self.__type == _Buffer.Types.TRIS and space_3d.shading.type == 'WIREFRAME': return self.__bgl_callback(self.__bgl_callback_param_before) # bind shader self.__shader.bind() # fill the uniforms to binded shader for uniform_name, uniform_type, uniform_data, uniform_length, uniform_count in uniforms: uniform_loc = self.__shader.uniform_from_name(uniform_name) if uniform_type == float: self.__shader.uniform_vector_float(uniform_loc, uniform_data, uniform_length, uniform_count) elif uniform_type == int: self.__shader.uniform_vector_int(uniform_loc, uniform_data, uniform_length, uniform_count) else: raise TypeError("Invalid uniform type: %s" % uniform_type) # create batch and dispatch draw batch = batch_for_shader(self.__shader, self.__draw_type, self.__data) batch.draw(self.__shader) self.__bgl_callback(self.__bgl_callback_param_after)
def screen_v3d_batch_matrix_overlay(context, args): region = context.region region3d = context.space_data.region_3d cdat, alpha = args[0], args[1] if not alpha > 0.0: return pt = 0.5 G = -0.001 # to z offset the plane from the axis coords = (-pt, pt, G), (pt, pt, G), (pt, -pt, G), (-pt, -pt, G) indices_plane = [(0, 1, 2), (0, 2, 3)] # first calculate positions and lerp colors coords_transformed = [] indices_shifted = [] idx_offset = 0 colors = [] for i, (matrix, color) in enumerate(cdat): r, g, b = color for x, y, z in coords: vector3d = matrix @ Vector((x, y, z)) vector2d = loc3d2d(region, region3d, vector3d) coords_transformed.append(vector2d) colors.append((r, g, b, alpha)) for indices in indices_plane: indices_shifted.append(tuple(idx + idx_offset for idx in indices)) idx_offset += 4 batch = batch_for_shader(smooth_2d_shader, 'TRIS', { "pos": coords_transformed, "color": colors }, indices=indices_shifted) # smooth_2d_shader.bind() batch.draw(smooth_2d_shader)
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 shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') bgl.glEnable(bgl.GL_BLEND) bgl.glLineWidth(2) batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": self.mouse_path}) shader.bind() shader.uniform_float("color", (0.0, 0.0, 0.0, 0.5)) batch.draw(shader) # restore opengl defaults bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND)
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 shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') gpu.state.blend_set('ALPHA') gpu.state.line_width_set(2.0) batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": self.mouse_path}) shader.bind() shader.uniform_float("color", (0.0, 0.0, 0.0, 0.5)) batch.draw(shader) # restore opengl defaults gpu.state.line_width_set(1.0) gpu.state.blend_set('NONE')
def draw_dome_light(ob): _SHADER_.bind() set_selection_color(ob) loc, rot, sca = Matrix(ob.matrix_world).decompose() axis,angle = rot.to_axis_angle() m = Matrix.Rotation(angle, 4, axis) m = m @ Matrix.Scale(100, 4) sphere = make_sphere(m) sphere_indices = [] for i in range(0, len(sphere)): if i == len(sphere)-1: sphere_indices.append((i, 0)) else: sphere_indices.append((i, i+1)) batch = batch_for_shader(_SHADER_, 'LINES', {"pos": sphere}, indices=sphere_indices) batch.draw(_SHADER_)
def get_axes_batch(): vertices = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) vertex_colors = ((0.5, 0.5, 0.5, 0.0), (1.0, 0.0, 0.0, 0.6), (0.0, 1.0, 0.0, 0.6), (0.0, 0.0, 1.0, 0.6)) indices = ((0, 1), (0, 2), (0, 3)) shader_axes = engine.shaders.getShader("axes") batch_axes = batch_for_shader( shader_axes, 'LINES', { "pos": vertices, "color": vertex_colors }, indices=indices, ) return batch_axes
def draw_shader(self, color, alpha, type, coords, size=1, indices=None): """ Create a batch for a draw type """ bgl.glEnable(bgl.GL_BLEND) bgl.glEnable(bgl.GL_LINE_SMOOTH) bgl.glPointSize(size) bgl.glLineWidth(size) try: if len(coords[0])>2: shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') else: shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, type, {"pos": coords}, indices=indices) shader.bind() shader.uniform_float("color", (color[0], color[1], color[2], alpha)) batch.draw(shader) bgl.glLineWidth(1) bgl.glPointSize(1) bgl.glDisable(bgl.GL_LINE_SMOOTH) bgl.glDisable(bgl.GL_BLEND) except: exc_type, exc_value, exc_traceback = sys.exc_info() self.report({'ERROR'}, str(exc_value))
def update(self, verts, faces, context): normals = [] vertices = [] for f in faces: vertices += [ verts[f[0]], verts[f[1]], verts[f[2]], verts[f[0]], verts[f[2]], verts[f[3]] ] a = Vector(verts[f[1]]) - Vector(verts[f[0]]) b = Vector(verts[f[2]]) - Vector(verts[f[0]]) nrm = (a.cross(b)).normalized() normals += [nrm] * 6 self.batch = batch_for_shader(self.shader, "TRIS", { "pos": vertices, "nrm": normals }) if self.draw_handler is None: self.draw_handler = bpy.types.SpaceView3D.draw_handler_add( self.draw, (self, context), 'WINDOW', 'POST_VIEW')
def draw(): print('drawing') context = bpy.context region = context.region xwin1, ywin1 = region.view2d.region_to_view(0, 0) xwin2, ywin2 = region.view2d.region_to_view(region.width, region.height) curx, cury = region.view2d.region_to_view(1, 0) curx = curx - xwin1 vertices = () indices = () #strip n = 0 for strip in bpy.context.scene.sequence_editor.sequences_all: # Strip coords x1, y1, x2, y2 = get_strip_rectf(strip) v1 = region.view2d.view_to_region(x1, y1, clip=False) v2 = region.view2d.view_to_region(x2, y1, clip=False) v3 = region.view2d.view_to_region(x1, y2, clip=False) v4 = region.view2d.view_to_region(x2, y2, clip=False) #### la partie intéressante ##### vertices += (v1, v2, v3, v4) indices += ((n, n + 1, n + 2), (n + 2, n + 1, n + 3)) n += 4 #### fin de la partie intéressante ##### shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices) shader.bind() shader.uniform_float("color", (0, 0.5, 0.5, 1.0)) batch.draw(shader)
def DrawNorth_callback(self, context): if not Sun.SP.ShowNorth and North.isActive: North.deactivate() return # ------------------------------------------------------------------ # Set up the compass needle using the current north offset angle # less 90 degrees. This forces the unit circle to begin at the # 12 O'clock instead of 3 O'clock position. # ------------------------------------------------------------------ color = (0.2, 0.6, 1.0, 1) radius = 100 angle = -(Sun.NorthOffset - math.pi / 2) x = math.cos(angle) * radius y = math.sin(angle) * radius bgl.glEnable(bgl.GL_MULTISAMPLE) bgl.glEnable(bgl.GL_LINE_SMOOTH) bgl.glEnable(bgl.GL_BLEND) bgl.glEnable(bgl.GL_DEPTH_TEST) bgl.glDepthMask(False) bgl.glLineWidth(2) p1 = (0, 0, 0) p2 = (x / 20, y / 20, 0) coords = [p1, p2] # Start & end of needle arclengths = [0, (Vector(p1) - Vector(p2)).length] batch = batch_for_shader(dashedLineShader, 'LINES', { "pos": coords, "arcLength": arclengths }) dashedLineShader.bind() dashedLineShader.uniform_float("finalColor", color) dashedLineShader.uniform_float("u_Scale", 10) batch.draw(dashedLineShader)
def draw_ui(self, context): x, y = self.start_mouse_position object = context.active_object set_drawing_dpi(get_dpi()) factor = get_dpi_factor() color_text1 = Hops_text_color() color_text2 = Hops_text2_color() color_border = Hops_border_color() color_border2 = Hops_border2_color() vertices = ( (x - 1 * factor, y + 23 * factor), (x - 1 * factor, y + 4 * factor), (x + 72 * factor, y + 23 * factor), (x + 72 * factor, y + 4 * factor), (x + 75 * factor, y + 23 * factor), (x + 75 * factor, y + 4 * factor), (x + 197 * factor, y + 23 * factor), (x + 197 * factor, y + 4 * factor), (x + 200 * factor, y + 23 * factor), (x + 200 * factor, y + 4 * factor), (x + 270 * factor, y + 23 * factor), (x + 270 * factor, y + 4 * factor)) indices = ( (0, 1, 2), (1, 2, 3), (4, 5, 6), (5, 6, 7), (8, 9, 10), (9, 10, 11)) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices) shader.bind() shader.uniform_float("color", (0.17, 0.17, 0.17, 1)) glEnable(GL_BLEND) batch.draw(shader) glDisable(GL_BLEND) draw_text("{:.3f}".format(context.object.data.bevel_depth), x + 27 * factor, y + 9 * factor, size=12, color=(0.831, 0.831, 0.831, 1)) draw_text("Segments (ctrl) - {:.0f}".format(context.object.data.render_resolution_u), x + 85 * factor, y + 9 * factor, size=12, color=(0.831, 0.831, 0.831, 1)) draw_text("Profile:{:.0f}".format(context.object.data.bevel_resolution), x + 210 * factor, y + 9 * factor, size=12, color=(0.831, 0.831, 0.831, 1)) self.draw_help(context, x, y, factor)
def create_batch(self, mouse_pos=None): points = self.get_vertices_copy(mouse_pos) points_mirror = self.get_vertices_mirror_copy(mouse_pos) extrude_points = self.get_vertices_extruded_copy(mouse_pos) extrude_points_m = self.get_vertices_extruded_mirror_copy(mouse_pos) extrude_lines = [] for index, vertex in enumerate(extrude_points): extrude_lines.append(points[index]) extrude_lines.append(vertex) extrude_lines_m = [] for index, vertex in enumerate(extrude_points_m): extrude_lines_m.append(points_mirror[index]) extrude_lines_m.append(vertex) self.batch = batch_for_shader(self.shader, 'LINE_LOOP', {"pos": points}) self.batch_extruded = batch_for_shader(self.shader, 'LINE_LOOP', {"pos": extrude_points}) self.batch_lines_extruded = batch_for_shader(self.shader, 'LINES', {"pos": extrude_lines}) # Mirror batches self.batch_mirror = batch_for_shader(self.shader, 'LINE_LOOP', {"pos": points_mirror}) self.batch_extruded_m = batch_for_shader(self.shader, 'LINE_LOOP', {"pos": extrude_points_m}) self.batch_lines_extruded_m = batch_for_shader( self.shader, 'LINES', {"pos": extrude_lines_m}) # Batch for points self.batch_points = batch_for_shader(self.shader, 'POINTS', {"pos": points})
def __init__(self, context, text): bakefile = "TLM_Overlay.png" scriptDir = os.path.dirname(os.path.realpath(__file__)) bakefile_path = os.path.abspath( os.path.join(scriptDir, '..', '..', 'assets/' + bakefile)) bpy.ops.image.open(filepath=bakefile_path) #print("Self path: " + bakefile_path) image_name = "TLM_Overlay.png" image = bpy.data.images[image_name] x = 15 y = 15 w = 400 h = 200 self.shader = gpu.shader.from_builtin('2D_IMAGE') self.batch = batch_for_shader( self.shader, 'TRI_FAN', { "pos": ((x, y), (x + w, y), (x + w, y + h), (x, y + h)), "texCoord": ((0, 0), (1, 0), (1, 1), (0, 1)), }, ) if image.gl_load(): raise Exception() self.text = text self.image = image #self.handle = bpy.types.SpaceView3D.draw_handler_add(self.draw_text_callback, (context,), 'WINDOW', 'POST_PIXEL') self.handle2 = bpy.types.SpaceView3D.draw_handler_add( self.draw_image_callback, (context, ), 'WINDOW', 'POST_PIXEL')
def draw_image(self): if self.__image is not None: try: y_screen_flip = self.get_area_height() - self.y_screen off_x, off_y = self.__image_position sx, sy = self.__image_size # bottom left, top left, top right, bottom right vertices = ((self.x_screen + off_x, y_screen_flip - off_y), (self.x_screen + off_x, y_screen_flip - sy - off_y), (self.x_screen + off_x + sx, y_screen_flip - sy - off_y), (self.x_screen + off_x + sx, y_screen_flip - off_y)) self.shader_img = gpu.shader.from_builtin('2D_IMAGE') self.batch_img = batch_for_shader( self.shader_img, 'TRI_FAN', { "pos": vertices, "texCoord": ((0, 1), (0, 0), (1, 0), (1, 1)) }, ) bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.__image.bindcode) self.shader_img.bind() self.shader_img.uniform_int("image", 0) self.batch_img.draw(self.shader_img) return True except: pass return False
def load_icon(image): shader = gpu.shader.from_builtin('2D_IMAGE') batch = batch_for_shader( shader, 'TRI_FAN', { "pos": ((100, 100), (128, 100), (128, 128), (100, 128)), "texCoord": ((0, 0), (1, 0), (1, 1), (0, 1)), }, ) if image.gl_load(): raise Exception() def draw(): bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, image.bindcode) shader.bind() shader.uniform_int("image", 0) batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_PIXEL')
def draw(): coords = [] for v, o in zip(vectors, origins): coords.append(mx @ o) coords.append(mx @ o + mx.to_3x3() @ v) indices = [(i, i + 1) for i in range(0, len(coords), 2)] shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') shader.bind() shader.uniform_float("color", (*color, alpha)) gpu.state.depth_test_set('NONE' if xray else 'LESS_EQUAL') gpu.state.blend_set('ALPHA' if alpha < 1 else 'NONE') gpu.state.line_width_set(width) use_legacy_line_smoothing(alpha, width) batch = batch_for_shader(shader, 'LINES', {"pos": coords}, indices=indices) batch.draw(shader)
def onscreen_gem_table(self, x, y, color=(0.97, 0.97, 0.97, 1.0)): fontid = 1 blf.size(fontid, self.prefs.view_font_size_report, 72) blf.color(fontid, *color) _, font_h = blf.dimensions(fontid, "Row Height") font_baseline = font_h * 0.4 font_row_height = font_h * 2 box_size = font_h * 1.5 y += font_baseline for row, color in self.gems_fmt: y -= font_row_height shader.bind() shader.uniform_float("color", color) batch_font = batch_for_shader(shader, "TRI_FAN", {"pos": self.rect_coords(x, y, box_size, box_size)}) batch_font.draw(shader) blf.position(fontid, x + font_row_height, y + font_baseline, 0.0) blf.draw(fontid, row) return y
def draw_image(x, y, width, height, image, transparency): # draw_rect(x,y, width, height, (.5,0,0,.5)) coords = [(x, y), (x + width, y), (x, y + height), (x + width, y + height)] uvs = [(0, 0), (1, 0), (0, 1), (1, 1)] indices = [(0, 1, 2), (2, 1, 3)] shader = gpu.shader.from_builtin('2D_IMAGE') batch = batch_for_shader(shader, 'TRIS', { "pos": coords, "texCoord": uvs }, indices=indices) # send image to gpu if it isn't there already if image.gl_load(): raise Exception() # texture identifier on gpu texture_id = image.bindcode # in case someone disabled it before bgl.glEnable(bgl.GL_BLEND) # bind texture to image unit 0 bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture_id) shader.bind() # tell shader to use the image that is bound to image unit 0 shader.uniform_int("image", 0) batch.draw(shader) bgl.glDisable(bgl.GL_TEXTURE_2D)
def prep_pole_batch(self, shader, mesh, obj): if obj.mode == 'EDIT': bm = bmesh.from_edit_mesh(obj.data) else: bm = bmesh.new() bm.from_mesh(obj.data) bm.verts.ensure_lookup_table() bm.edges.ensure_lookup_table() bm.faces.ensure_lookup_table() pole_verts = [vert for vert in bm.verts if len(vert.link_edges) > 4] pole_coords = [] pole_indices = [] pole_idx = 0 for vert in pole_verts: pole_coords.append(vert.co) smallest_dimension = self.get_smallest_vector_dimension( obj.dimensions) pole_coords.append(vert.co + vert.normal * smallest_dimension * 0.5 * obj.rv_poles_size) pole_indices.append([pole_idx, pole_idx + 1]) pole_idx += 2 pole_color = (obj.rv_poles_color.r, obj.rv_poles_color.g, obj.rv_poles_color.b, 1) pole_colors = [pole_color for _ in pole_coords] return batch_for_shader(shader, 'LINES', { "position": pole_coords, "color": pole_colors }, indices=pole_indices)
def reg_draw_callback(self, order, render=True): if self.sources is None: return self.dereg_draw_callback() if render: indices_eff = [] for si, s in enumerate(self.sources): nhist = len(s.rays[0].refpts_hist) + 1 idx_eff = self.rays[si]['indices'] idx_eff = idx_eff.reshape((idx_eff.shape[0]//(nhist-1), -1)) idx_eff = idx_eff[:, :order*2].reshape((-1, 2)) indices_eff.append(idx_eff) shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') draw_data = [] for ri, r in enumerate(self.rays): h = cc.glasbey[ri % len(cc.rainbow)].lstrip('#') draw_data.append({ 'batch': batch_for_shader( shader, 'LINES', {'pos': r['positions']}, indices=indices_eff[ri] ), 'color': tuple( int(h[i:i+2], 16) / 256.0 for i in (0, 2, 4) ) + (1,) }) def draw(): shader.bind() for d in draw_data: shader.uniform_float("color", d['color']) d['batch'].draw(shader) self.gldraw_handler = bpy.types.SpaceView3D.draw_handler_add( draw, (), 'WINDOW', 'POST_VIEW' )
def draw_ui(self, context): x, y = self.start_mouse_position object = context.active_object set_drawing_dpi(get_dpi()) factor = get_dpi_factor() color_text1 = Hops_text_color() color_text2 = Hops_text2_color() color_border = Hops_border_color() color_border2 = Hops_border2_color() vertices = ((x - 1 * factor, y + 23 * factor), (x - 1 * factor, y + 4 * factor), (x + 140 * factor, y + 23 * factor), (x + 140 * factor, y + 4 * factor)) indices = ((0, 1, 2), (1, 2, 3)) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices) shader.bind() shader.uniform_float("color", (0.17, 0.17, 0.17, 1)) glEnable(GL_BLEND) batch.draw(shader) glDisable(GL_BLEND) draw_text(" {:.2f} - B-Weight".format(self.value), x + 27 * factor, y + 9 * factor, size=12, color=(0.831, 0.831, 0.831, 1)) self.draw_help(context, x, y, factor)
def show(self, object_matrix: Matrix, initial_centroid_matrix: Matrix, filtering_display_mode: str) -> None: """Setup shaders and other required data to display the point cloud. Arguments: object_matrix {bpy.types.Object} -- user interface handle object matrix initial_centroid_matrix {Matrix} -- initial centroid matrix of the recontruction filtering_display_mode {str} -- point cloud filtering diplay mode, from {sfm_flow.reconstruction.SFMFLOW_ReconstructionModelProperties} """ if filtering_display_mode == "cloud_filter.color": # override colors for discarded points positions = self.vertices colors = self.colors.copy() colors[self._discard_vertices] = self.filtered_points_color elif filtering_display_mode == "cloud_filter.filtered": # show only points that are not discarded positions = self.vertices_filtered colors = self.colors_filtered else: # default to "cloud_filter.all" # show all vertices with original colors positions = self.vertices colors = self.colors # # setup shader self._shader = GPUShader(PointCloud._vertex_shader, PointCloud._fragment_shader) self._batch = batch_for_shader( self._shader, 'POINTS', { "position": positions, "color": colors }, ) self._object_matrix = object_matrix self._initial_centroid_matrix = initial_centroid_matrix
def draw(self): if not self.valid_crop_window(): return self.crop_windowing = True vertices = [self.cw_c1,self.cw_c2,self.cw_c3,self.cw_c4] indices = [(0, 1), (1, 2), (2,3), (3, 0)] # draw delete box if self.__edit_cropwindow: x0 = self.cw_c3[0] y0 = self.cw_c3[1] x1 = x0+ 10 y1 = y0 + 10 self.del_c1 = (x0, y0 ) self.del_c2 = (x1, y0) self.del_c3 = (x1, y1) self.del_c4 = (x0, y1) vertices.append(self.del_c1) vertices.append(self.del_c2) vertices.append(self.del_c3) vertices.append(self.del_c4) indices.append((4, 5)) indices.append((5,6)) indices.append((6,7)) indices.append((7,4)) indices.append((7,5)) indices.append((6,4)) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos": vertices}, indices=indices) shader.bind() shader.uniform_float("color", get_pref('rman_viewport_crop_color', default=(0.0, 0.498, 1.0, 1.0))) batch.draw(shader)
def draw_callback_bezier_3d(self, context): bgl.glEnable(bgl.GL_BLEND) bgl.glDepthFunc(bgl.GL_ALWAYS) bezier = self.beziers[self.spline_id][self.bezier_id] split = bezier.split(self.at) points = bezier.points bgl.glLineWidth(1.0) shader.bind() shader.uniform_float("color", (1, 1, 1, 0.5)) batch = batch_for_shader(shader, 'LINES', {"pos": points}) batch.draw(shader) bgl.glPointSize(6) shader.uniform_float("color", (1, 1, 1, 1)) batch = batch_for_shader(shader, 'POINTS', {"pos": [points[0], points[3]]}) batch.draw(shader) bgl.glPointSize(2) batch = batch_for_shader(shader, 'POINTS', {"pos": [points[1], points[2]]}) batch.draw(shader) # draw new bezier anchor bgl.glLineWidth(2) shader.uniform_float("color", (0.8, 1.0, 0.0, 0.5)) batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": [split[2], split[3], split[4]]}) batch.draw(shader) bgl.glPointSize(10) shader.uniform_float("color", (0.2, 1, 0.0, 1.0)) batch = batch_for_shader(shader, 'POINTS', {"pos": [split[3]]}) batch.draw(shader) bgl.glPointSize(6) batch = batch_for_shader(shader, 'POINTS', {"pos": [split[2], split[4]]}) batch.draw(shader) # gl end and restore bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) bgl.glEnable(bgl.GL_DEPTH_TEST) bgl.glPointSize(1)
def prep_wireframe_batch(self, shader, mesh, obj, vert_idx_cache, edge_indices): coords = np.empty((len(mesh.vertices), 3), 'f') mesh.vertices.foreach_get("co", np.reshape(coords, len(mesh.vertices) * 3)) # offset wireframe verts to have slightly different depth - works well only for close view range for c_idx, coord in enumerate(coords): coords[c_idx] = coord + mesh.vertices[c_idx].normal * 0.0035 wireframe_colors = np.empty((len(mesh.vertices), 4), 'f') for v_idx, _ in enumerate(mesh.vertices): wireframe_colors[v_idx] = ( 0, 0, 0, obj.rv_groups_alpha) if v_idx in vert_idx_cache else (0, 0, 0, 0) return batch_for_shader(shader, 'LINES', { "position": coords, "color": wireframe_colors }, indices=edge_indices)
def draw_callback_3d(cameras): bgl.glPointSize(4) bgl.glEnable(bgl.GL_BLEND) coords = [] colors = [] for cam in cameras: if cam['camera_data'].camera_frustum_settings.enable: for co in cam["co"]: coords.append(co) colors.append(list(cam["color"]) + [0.5]) batch = batch_for_shader(shader, 'POINTS', { "pos": coords, "color": colors }) shader.bind() batch.draw(shader) # Restore opengl defaults bgl.glPointSize(1) bgl.glDisable(bgl.GL_BLEND)
def draw_matrices(matrices, scale, with_bounding_box): x_p = Vector((scale, 0.0, 0.0)) x_n = Vector((-scale, 0.0, 0.0)) y_p = Vector((0.0, scale, 0.0)) y_n = Vector((0.0, -scale, 0.0)) z_p = Vector((0.0, 0.0, scale)) z_n = Vector((0.0, 0.0, -scale)) red_dark = (0.2, 0.0, 0.0, 1.0) red_light = (1.0, 0.2, 0.2, 1.0) green_dark = (0.0, 0.2, 0.0, 1.0) green_light = (0.2, 1.0, 0.2, 1.0) blue_dark = (0.0, 0.0, 0.2, 1.0) blue_light = (0.4, 0.4, 1.0, 1.0) coords = [] colors = [] for matrix in matrices: coords.append(matrix @ x_n) coords.append(matrix @ x_p) colors.extend((red_dark, red_light)) coords.append(matrix @ y_n) coords.append(matrix @ y_p) colors.extend((green_dark, green_light)) coords.append(matrix @ z_n) coords.append(matrix @ z_p) colors.extend((blue_dark, blue_light)) batch = batch_for_shader(smooth_color_shader, "LINES", { "pos": coords, "color": colors }) batch.draw(smooth_color_shader) if with_bounding_box: draw_bounding_boxes(matrices, scale, (1.0, 1.0, 1.0, 1.0))
def draw_trajectory(): context = bpy.context data = bpy.data draw_trajectories = context.scene.projectile_settings.draw_trajectories if draw_trajectories == 'all': emitters = [ob for ob in data.objects if ob.projectile_props.is_emitter] else: # Only draw selected emitters = [ob for ob in context.selected_objects if ob.projectile_props.is_emitter] # Generate a list of all coordinates for all trajectories coordinates = [] for emitter in emitters: coordinates += calculate_trajectory(context, emitter) # Draw all trajectories shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos": coordinates}) shader.bind() shader.uniform_float("color", (1, 1, 1, 1)) batch.draw(shader)
""" 3D Lines with Single Color -------------------------- """ import bpy import gpu from gpu_extras.batch import batch_for_shader coords = [(1, 1, 1), (-2, 0, 0), (-2, -1, 3), (0, 1, 1)] shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos": coords}) def draw(): shader.bind() shader.uniform_float("color", (1, 1, 0, 1)) batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')
""" 2D Rectangle ------------ """ import bpy import gpu from gpu_extras.batch import batch_for_shader vertices = ( (100, 100), (300, 100), (100, 200), (300, 200)) indices = ( (0, 1, 2), (2, 1, 3)) shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices) def draw(): shader.bind() shader.uniform_float("color", (0, 0.5, 0.5, 1.0)) batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_PIXEL')
To use this example you have to provide an image that should be displayed. """ import bpy import gpu import bgl from gpu_extras.batch import batch_for_shader IMAGE_NAME = "Untitled" image = bpy.data.images[IMAGE_NAME] shader = gpu.shader.from_builtin('2D_IMAGE') batch = batch_for_shader( shader, 'TRI_FAN', { "pos": ((100, 100), (200, 100), (200, 200), (100, 200)), "texCoord": ((0, 0), (1, 0), (1, 1), (0, 1)), }, ) if image.gl_load(): raise Exception() def draw(): bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, image.bindcode) shader.bind() shader.uniform_int("image", 0) batch.draw(shader)
pos = position; gl_Position = viewProjectionMatrix * vec4(position, 1.0f); } ''' fragment_shader = ''' uniform float brightness; in vec3 pos; void main() { gl_FragColor = vec4(pos * brightness, 1.0); } ''' coords = [(1, 1, 1), (2, 0, 0), (-2, -1, 3)] shader = gpu.types.GPUShader(vertex_shader, fragment_shader) batch = batch_for_shader(shader, 'TRIS', {"position": coords}) def draw(): shader.bind() matrix = bpy.context.region_data.perspective_matrix shader.uniform_float("viewProjectionMatrix", matrix) shader.uniform_float("brightness", 0.5) batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')
def draw_rect_3d(coords, color): indices = [(0, 1, 2), (2, 3, 0)] shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'TRIS', {"pos": coords}, indices=indices) shader.uniform_float("color", color) batch.draw(shader)
import numpy as np from random import random from gpu_extras.batch import batch_for_shader mesh = bpy.context.active_object.data mesh.calc_loop_triangles() vertices = np.empty((len(mesh.vertices), 3), 'f') indices = np.empty((len(mesh.loop_triangles), 3), 'i') mesh.vertices.foreach_get( "co", np.reshape(vertices, len(mesh.vertices) * 3)) mesh.loop_triangles.foreach_get( "vertices", np.reshape(indices, len(mesh.loop_triangles) * 3)) vertex_colors = [(random(), random(), random(), 1) for _ in range(len(mesh.vertices))] shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR') batch = batch_for_shader( shader, 'TRIS', {"pos": vertices, "color": vertex_colors}, indices=indices, ) def draw(): batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')
void main() { if (step(sin(v_ArcLength * u_Scale), 0.5) == 1) discard; gl_FragColor = vec4(1.0); } ''' coords = [Vector((random(), random(), random())) * 5 for _ in range(5)] arc_lengths = [0] for a, b in zip(coords[:-1], coords[1:]): arc_lengths.append(arc_lengths[-1] + (a - b).length) shader = gpu.types.GPUShader(vertex_shader, fragment_shader) batch = batch_for_shader( shader, 'LINE_STRIP', {"position": coords, "arcLength": arc_lengths}, ) def draw(): shader.bind() matrix = bpy.context.region_data.perspective_matrix shader.uniform_float("u_ViewProjectionMatrix", matrix) shader.uniform_float("u_Scale", 10) batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')
def batch_create(self, coords): batch = batch_for_shader(self.shader, 'TRIS', {"pos": coords, "texCoord": self.uvs}, indices=self.indices) return batch
def glEnd(): inst = InternalData.get_instance() color = inst.get_color() coords = inst.get_verts() tex_coords = inst.get_tex_coords() if inst.get_dims() == 2: if len(tex_coords) == 0: shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR') else: #shader = gpu.shader.from_builtin('2D_IMAGE') vert_shader, frag_shader = _get_transparency_shader() shader = gpu.types.GPUShader(vert_shader, frag_shader) else: raise NotImplemented("get_dims() != 2") if len(tex_coords) == 0: data = { "pos": coords, } else: data = { "pos": coords, "texCoord": tex_coords } if inst.get_prim_mode() == GL_LINES: indices = [] for i in range(0, len(coords), 2): indices.append([i, i + 1]) batch = batch_for_shader(shader, 'LINES', data, indices=indices) elif inst.get_prim_mode() == GL_LINE_STRIP: batch = batch_for_shader(shader, 'LINE_STRIP', data) elif inst.get_prim_mode() == GL_LINE_LOOP: data["pos"].append(data["pos"][0]) batch = batch_for_shader(shader, 'LINE_STRIP', data) elif inst.get_prim_mode() == GL_TRIANGLES: indices = [] for i in range(0, len(coords), 3): indices.append([i, i + 1, i + 2]) batch = batch_for_shader(shader, 'TRIS', data, indices=indices) elif inst.get_prim_mode() == GL_TRIANGLE_FAN: indices = [] for i in range(1, len(coords) - 1): indices.append([0, i, i + 1]) batch = batch_for_shader(shader, 'TRIS', data, indices=indices) elif inst.get_prim_mode() == GL_QUADS: indices = [] for i in range(0, len(coords), 4): indices.extend([[i, i + 1, i + 2], [i + 2, i + 3, i]]) batch = batch_for_shader(shader, 'TRIS', data, indices=indices) else: raise NotImplemented("get_prim_mode() != (GL_LINES|GL_TRIANGLES|GL_QUADS)") shader.bind() if len(tex_coords) != 0: shader.uniform_float("modelViewMatrix", gpu.matrix.get_model_view_matrix()) shader.uniform_float("projectionMatrix", gpu.matrix.get_projection_matrix()) shader.uniform_int("image", 0) shader.uniform_float("color", color) batch.draw(shader) inst.clear()
fragment_shader = ''' uniform sampler2D image; in vec2 uvInterp; void main() { gl_FragColor = texture(image, uvInterp); } ''' shader = gpu.types.GPUShader(vertex_shader, fragment_shader) batch = batch_for_shader( shader, 'TRI_FAN', { "position": ((-1, -1), (1, -1), (1, 1), (-1, 1)), "uv": ((0, 0), (1, 0), (1, 1), (0, 1)), }, ) def draw(): bgl.glActiveTexture(bgl.GL_TEXTURE0) bgl.glBindTexture(bgl.GL_TEXTURE_2D, offscreen.color_texture) shader.bind() shader.uniform_float("modelMatrix", Matrix.Translation((1, 2, 3)) @ Matrix.Scale(3, 4)) shader.uniform_float("viewProjectionMatrix", bpy.context.region_data.perspective_matrix) shader.uniform_float("image", 0) batch.draw(shader)
""" Wireframe Cube using Index Buffer --------------------------------- """ import bpy import gpu from gpu_extras.batch import batch_for_shader coords = ( (-1, -1, -1), (+1, -1, -1), (-1, +1, -1), (+1, +1, -1), (-1, -1, +1), (+1, -1, +1), (-1, +1, +1), (+1, +1, +1)) indices = ( (0, 1), (0, 2), (1, 3), (2, 3), (4, 5), (4, 6), (5, 7), (6, 7), (0, 4), (1, 5), (2, 6), (3, 7)) shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') batch = batch_for_shader(shader, 'LINES', {"pos": coords}, indices=indices) def draw(): shader.bind() shader.uniform_float("color", (1, 0, 0, 1)) batch.draw(shader) bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')