def draw(self): self.canvas.clear() with self.canvas: Color(self.color.r, self.color.g, self.color.b) # half-circle Ellipse(pos=(self.position.x - TankWidget.tank_size / 2, self.position.y - TankWidget.tank_size / 2), size=(TankWidget.tank_size, TankWidget.tank_size), angle_start=-90, angle_end=90, segments=30) # base Rectangle(pos=(self.position.x - TankWidget.tank_size / 2, self.position.y - TankWidget.tank_size / 4), size=(TankWidget.tank_size, TankWidget.tank_size / 4)) # barrel PushMatrix() self.rot = Rotate() self.rot.angle = self.barrel_rotation self.rot.origin = (self.position.x, self.position.y) Rectangle(pos=(self.position.x - TankWidget.tank_barrel_size.x / 2, self.position.y), size=(TankWidget.tank_barrel_size.x, TankWidget.tank_size / 2 + TankWidget.tank_barrel_size.y)) PopMatrix()
def __init__(self, **kwargs): # Make sure opengl context exists EventLoop.ensure_window() self.canvas = RenderContext(use_parent_projection=True, use_parent_modelview=True) self._callbacks = {} with self.canvas: self.fbo = Fbo(size=self.size) with self.fbo.before: # noqa PushMatrix() with self.fbo: ClearColor(0, 0, 0, 0) ClearBuffers() self._background_color = Color(*self.background_color) self.fbo_rectangle = Rectangle(size=self.size) with self.fbo.after: # noqa PopMatrix() super(EffectWidget, self).__init__(**kwargs) fbind = self.fbind fbo_setup = self.refresh_fbo_setup fbind('size', fbo_setup) fbind('effects', fbo_setup) fbind('background_color', self._refresh_background_color) self.refresh_fbo_setup() self._refresh_background_color() # In case thi was changed in kwargs
def _set_canvas(self): with self.canvas.before: PushMatrix() self.rotation = Rotate(angle=self.start_angle, origin=self.center) with self.canvas.after: PopMatrix()
def on_update(self, *args, **kwargs): if self.parent is None: return cell_x = self.parent.size[0] / self.parent.sizeX cell_y = self.parent.size[1] / self.parent.sizeY agent_pos = self.agent.get_position() (ppos_x, ppos_y) = self.parent.pos self.pos = (int(agent_pos['x'] * cell_x) + ppos_x, int(agent_pos['y'] * cell_y) + ppos_y) self.size_hint = (1 / self.parent.sizeX, 1 / self.parent.sizeY) self.source = 'images/icons8-truck-50.png' self.canvas.before.clear() self.canvas.after.clear() with self.canvas.before: if self.selected: self.draw_selected() PushMatrix() if self.agent.get_orientation_angle() == 180: pass Rotate(angle=self.agent.get_orientation_angle(), origin=self.center) with self.canvas.after: PopMatrix()
def show_precincts(self): precinct_graphics = self.precinct_graphics = {} with self.canvas: PushMatrix() Translate(self.focus_region_width, 0) for precinct in self.voronoi_mapping.precincts: assert len(precinct.boundary) >= 6 tess = Tesselator() tess.add_contour(precinct.boundary) tess.tesselate(WINDING_ODD, TYPE_POLYGONS) graphics = [ Color(rgba=(0, 0, 0, 1))] for vertices, indices in tess.meshes: graphics.append( Mesh( vertices=vertices, indices=indices, mode="triangle_fan")) graphics.append( Color(rgba=(0, 1, 0, 1))) graphics.append( Line(points=precinct.boundary, width=1)) precinct_graphics[precinct] = graphics PopMatrix()
def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None): '''Markers graphics instructions are stored on a dictionary and hashed through graphics context and rgbFace values. If a marker_path with the corresponding graphics context exist then the instructions are pulled from the markers dictionary. ''' if not len(path.vertices): return # get a string representation of the path path_data = self._convert_path( marker_path, marker_trans + Affine2D().scale(1.0, -1.0), simplify=False) # get a string representation of the graphics context and rgbFace. style = str(gc._get_style_dict(rgbFace)) dictkey = (path_data, str(style)) # check whether this marker has been created before. list_instructions = self._markers.get(dictkey) # creating a list of instructions for the specific marker. if list_instructions is None: polygons = marker_path.to_polygons(marker_trans) self._markers[dictkey] = self.get_path_instructions(gc, polygons, rgbFace=rgbFace) # Traversing all the positions where a marker should be rendered for vertices, codes in path.iter_segments(trans, simplify=False): if len(vertices): x, y = vertices[-2:] for widget, instructions in self._markers[dictkey]: widget.canvas.add(PushMatrix()) widget.canvas.add(Translate(x, y)) widget.canvas.add(instructions) widget.canvas.add(PopMatrix())
def draw(self, canvas: Union[RenderContext, InstructionGroup]): canvas.add(PushMatrix()) canvas.add(self.rotate) self.left.draw(canvas) self.right.draw(canvas) canvas.add(self.bg_rect) self.in_hand.draw(canvas) canvas.add(PopMatrix())
def __init__(self, voronoi_mapping=None, table_mode=False, align_mat=None, screen_offset=(0, 0), ros_bridge=None, district_blocks_fid=None, focus_block_fid=0, focus_block_logical_id=0, district_metrics_fn=None, state_metrics_fn=None, show_voronoi_boundaries=False, focus_metrics=[], focus_metric_width=100, focus_metric_height=100, screen_size=(1920, 1080), max_fiducials_per_district=5, visualize_metric_data=True, **kwargs): super(VoronoiWidget, self).__init__(**kwargs) self.voronoi_mapping = voronoi_mapping self.ros_bridge = ros_bridge self.district_blocks_fid = district_blocks_fid self.focus_block_fid = focus_block_fid self.focus_block_logical_id = focus_block_logical_id self.show_voronoi_boundaries = show_voronoi_boundaries self.max_fiducials_per_district = max_fiducials_per_district self.visualize_metric_data = visualize_metric_data self.focus_metrics = focus_metrics self.focus_metric_width = focus_metric_width self.focus_metric_height = focus_metric_height self.screen_size = screen_size self.n_focus_rows = rows = int(screen_size[1] // focus_metric_height) self.n_focus_cols = cols = int(math.ceil(len(focus_metrics) / rows)) self.focus_region_width = cols * focus_metric_width self.show_district_selection() self.show_focus_region() self.fiducial_graphics = {} self.fiducials_color = {} self.colors = cycle(plt.get_cmap('tab10').colors) self.table_mode = table_mode self.align_mat = align_mat self.district_graphics = [] self.district_metrics_fn = district_metrics_fn self.state_metrics_fn = state_metrics_fn self.screen_offset = screen_offset self.touches = {} with self.canvas.before: PushMatrix() Translate(*[v * Metrics.density for v in screen_offset]) with self.canvas.after: PopMatrix() self.show_precincts()
def __init__(self, angle=0, **kwargs): super(IconButton, self).__init__(**kwargs) self.rotate = Rotate(angle = angle) self.canvas.before.add(PushMatrix()) self.canvas.before.add(self.rotate) self.canvas.after.add(PopMatrix()) self.bind(pos=self.update_canvas) self.bind(size=self.update_canvas) self.guess = None
def _set_view(self): fx, fy = self.map.viewport.origin # clear any previous before/after instructions self.canvas.before.clear() self.canvas.after.clear() with self.canvas.before: PushMatrix('projection_mat') Translate(-fx, -fy) with self.canvas.after: PopMatrix('projection_mat')
def process_voronoi_output(self, districts, fiducial_identity, fiducial_pos, error=[], post_callback=None, largs=(), data_is_old=False): if data_is_old: return if post_callback is not None: post_callback(*largs) if not error: fid_ids = [self.district_blocks_fid[i] for i in fiducial_identity] if self.ros_bridge is not None: self.ros_bridge.update_voronoi(fiducial_pos, fid_ids, fiducial_identity, districts, self.district_metrics_fn, self.state_metrics_fn) if self.visualize_metric_data and self.current_focus_metric: for graphics in self.precinct_graphics.values(): graphics[0].a = 1. # undo possible previous error display else: if not districts: self.clear_voronoi() else: self.paint_precinct_by_district() if error: for precinct in error: self.precinct_graphics[precinct][0].a = 0 for item in self.district_graphics: self.canvas.remove(item) self.district_graphics = [] if self.show_voronoi_boundaries: with self.canvas: PushMatrix() Translate(self.focus_region_width, 0) Scale(Metrics.density) self.district_graphics.append(Color(1, 1, 0, 1)) for district in districts: if not district.boundary: continue self.district_graphics.append( Line(points=district.boundary + district.boundary[:2], width=2)) PopMatrix()
def rotate(self, angle): global start_angle with self.canvas.before: PushMatrix() self.rot = Rotate() self.rot.angle = angle - start_angle self.rot.origin = self.center self.rot.axis = (0, 0, 1) start_angle = angle with self.canvas.after: PopMatrix()
def draw_path_collection(self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): '''Draws a collection of paths selecting drawing properties from the lists *facecolors*, *edgecolors*, *linewidths*, *linestyles* and *antialiaseds*. *offsets* is a list of offsets to apply to each of the paths. The offsets in *offsets* are first transformed by *offsetTrans* before being applied. *offset_position* may be either "screen" or "data" depending on the space that the offsets are in. ''' len_path = len(paths[0].vertices) if len(paths) > 0 else 0 uses_per_path = self._iter_collection_uses_per_path( paths, all_transforms, offsets, facecolors, edgecolors) # check whether an optimization is needed by calculating the cost of # generating and use a path with the cost of emitting a path in-line. should_do_optimization = \ len_path + uses_per_path + 5 < len_path * uses_per_path if not should_do_optimization: return RendererBase.draw_path_collection( self, gc, master_transform, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position) # Generate an array of unique paths with the respective transformations path_codes = [] for i, (path, transform) in enumerate( self._iter_collection_raw_paths(master_transform, paths, all_transforms)): transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0) if _mpl_ge_2_0: polygons = path.to_polygons(transform, closed_only=False) else: polygons = path.to_polygons(transform) path_codes.append(polygons) # Apply the styles and rgbFace to each one of the raw paths from # the list. Additionally a transformation is being applied to # translate each independent path for xo, yo, path_poly, gc0, rgbFace in self._iter_collection( gc, master_transform, all_transforms, path_codes, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls, offset_position): list_canvas_instruction = self.get_path_instructions( gc0, path_poly, closed=True, rgbFace=rgbFace) for widget, instructions in list_canvas_instruction: widget.canvas.add(PushMatrix()) widget.canvas.add(Translate(xo, yo)) widget.canvas.add(instructions) widget.canvas.add(PopMatrix())
def __init__(self, **kwargs): super(ProgressImage, self).__init__(**kwargs) # self.x = x -- not necessary, x is a property and will be handled by super() self.source = self.root_path + '/img/spin.png' self.size_hint = (None, None) self.size = (60, 60) with self.canvas.before: PushMatrix() self.rot = Rotate() self.rot.angle = 0 self.rot.origin = self.center self.rot.axis = (0, 0, 1) with self.canvas.after: PopMatrix()
def process_voronoi_output( self, districts, fiducial_identity, fiducial_pos, error=[], post_callback=None, largs=(), data_is_old=False): if data_is_old: return if post_callback is not None: post_callback(*largs) if not error: self.district_metrics_fn(districts) state_metrics = self.state_metrics_fn(districts) fid_ids = [self.district_blocks_fid[i] for i in fiducial_identity] if self.ros_bridge is not None: self.ros_bridge.update_voronoi( fiducial_pos, fid_ids, fiducial_identity, districts, state_metrics) if not districts: self.clear_voronoi() return colors = self.fiducials_color for district in districts: color = colors[district.identity] for precinct in district.precincts: self.precinct_graphics[precinct][0].rgba = color + [1., ] if error: for precinct in error: self.precinct_graphics[precinct][0].a = .3 for item in self.district_graphics: self.canvas.remove(item) self.district_graphics = [] if self.show_voronoi_boundaries: PushMatrix() Translate(self.focus_region_width, 0) with self.canvas: self.district_graphics.append(Color(1, 1, 0, 1)) for district in districts: self.district_graphics.append( Line(points=district.boundary + district.boundary[:2], width=2)) PopMatrix()
def __init__(self, **kwargs): super(ApproveWidget, self).__init__(**kwargs) self.imageP = Image(pos=self.pos, size_hint=(1, 1), opacity=0, source='data/like_animation.png') self.imageN = Image(pos=self.pos, size_hint=(1, 1), opacity=0, source='data/dislike_animation.png') self.add_widget(self.imageP) self.add_widget(self.imageN) from kivy.graphics.context_instructions import PushMatrix, PopMatrix, MatrixInstruction self.transform = MatrixInstruction() self.canvas.before.add(PushMatrix()) self.canvas.before.add(self.transform) self.canvas.after.add(PopMatrix())
def setup_scene(self): Color(1, 0, 1, 1) PushMatrix() self.translate = Translate(0, -3, -10) self.rotx = Rotate(0, 1, 0, 0) self.rot = Rotate(0.5, 0, 1, 0) self.scale = Scale(1.0) #m = random.sample(xrange(10), 10)#list(self.scene.objects.values())[0] #m = list(self.scene.objects.values())[0] self.mesh = self.generateMesh() #Mesh( UpdateNormalMatrix() #self.mesh = Mesh( # vertices=m.vertices, # indices=m.indices, # fmt=m.vertex_format, # mode='triangles', #) PopMatrix()
def __init__(self, zs, ps, **kwargs): super(Renderer, self).__init__(**kwargs) self.canvas = RenderContext(compute_normal_mat=True) self.canvas.shader.source = resource_find('simple.glsl') #self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self.zs = zs self.ps = ps #self._keyboard.bind(on_key_down=self._on_keyboard_down) #self._keyboard.bind(on_key_up=self._on_keyboard_up) self.shiftDown = False #self.scene = ObjFile(resource_find("monkey.obj")) with self.canvas: self.cb = Callback(self.setup_gl_context) PushMatrix() self.setup_scene() PopMatrix() self.cb = Callback(self.reset_gl_context) Clock.schedule_interval(self.update_glsl, 1 / 60.)
def Render(self, matrix, colorTransform, renderingIndex, renderingCount, visible): if not visible or colorTransform.multi.alpha == 0: return # print(matrix) # print("") self.m_color.rgba = (colorTransform.multi.red, colorTransform.multi.green, colorTransform.multi.blue, colorTransform.multi.alpha) self.m_matrix.set(flat=[ matrix.scaleX, -matrix.skew0, 0, 0, # matrix.skew0, -matrix.skew0 -matrix.skew1, matrix.scaleY, 0, 0, # matrix.scaleX, matrix.scaleY 0, 0, 1, 0, matrix.translateX, matrix.translateY, 0, 1 ]) # matrix.translateX, matrix.translateY self.m_inst.matrix = self.m_matrix self.canvas.add(PushMatrix()) self.canvas.add(Color(1, 0, 0, 1)) self.canvas.add(Translate(575, 300)) self.canvas.add(Ellipse(size=(5, 5))) self.canvas.add(self.m_origin_transform) self.canvas.add(Ellipse(size=(5, 5))) self.canvas.add(Scale(1, -1, 1, origin=(0, 0))) self.canvas.add(self.m_inst) self.canvas.add(self.m_color) self.canvas.add(self.m_mesh) self.canvas.add(PopMatrix()) self.canvas.ask_update()
def __init__(self, car_idx, initial_destination, args): self.pos = (100, 100) self._idx = car_idx self._sand_speed = _PADDING / 5.0 self._full_speed = _PADDING / 4.0 self._velocity = self._full_speed self._last_action = 0 # index of _ROTATIONS self._direction = Vector(-1, 0) self._scores = [] self._orientation = 0.0 self._distance = 0.0 self._current_destination = initial_destination self._write_status_file = args.write_status_file if self._write_status_file: self._status_file = open("car{}_status".format(car_idx), "w") RelativeLayout.__init__(self) with self.canvas.before: PushMatrix() self._rotation = Rotate() with self.canvas.after: PopMatrix() self._center = Center() self._body = Body(Vector(-5, -5), _IDX_TO_COLOR[self._idx][0]) self._mid_sensor = Sensor(Vector(-30, -5), RGBAColor.RED, self._rotation) self._right_sensor = Sensor(Vector(-20, 10), RGBAColor.GREEN, self._rotation) self._left_sensor = Sensor(Vector(-20, -20), RGBAColor.BLUE, self._rotation) if args.use_pytorch: from torch_ai import Brain else: from simple_ai import Brain self._brain = Brain(len(self._state), len(self._ROTATIONS), args)
def on_angle(self, item, angle): """ Every time the angle of the item changes, this function is called to continue the rotation. Almost like a recursive function as each change in angle runs this which causes another change. :param item: the object being rotated :type: object :param angle: the angle at which the item's rotation will change to :type: int """ item.rotate_animation.stop(self) item.rotate_animation = Animation(angle=1, duration=0.00001) item.rotate_animation.start(self) if int(angle * 360) == 360: item.rotate_animation += Animation(angle=angle + 1, duration=0.00001) item.rotate_animation.start(self) with self.root.canvas.before: PushMatrix() Rotate(angle=angle, axis=(0, 0, 1), origin=self.root.center) with self.root.canvas.after: PopMatrix()
def __init__( self, voronoi_mapping=None, table_mode=False, align_mat=None, screen_offset=(0, 0), ros_bridge=None, district_blocks_fid=None, focus_block_fid=0, focus_block_logical_id=0, district_metrics_fn=None, state_metrics_fn=None, show_voronoi_boundaries=False, focus_metrics=[], focus_metric_width=100, focus_metric_height=100, screen_size=(1920, 1080), **kwargs): super(VoronoiWidget, self).__init__(**kwargs) self.voronoi_mapping = voronoi_mapping self.ros_bridge = ros_bridge self.district_blocks_fid = district_blocks_fid self.focus_block_fid = focus_block_fid self.focus_block_logical_id = focus_block_logical_id self.show_voronoi_boundaries = show_voronoi_boundaries self.focus_metrics = focus_metrics self.focus_metric_width = focus_metric_width self.focus_metric_height = focus_metric_height self.screen_size = screen_size self.n_focus_rows = rows = int(screen_size[1] // focus_metric_height) self.n_focus_cols = cols = int(math.ceil(len(focus_metrics) / rows)) self.focus_region_width = cols * focus_metric_width if not self.table_mode: spinner = self.gui_touch_spinner = GuiTouchClassSpinner( district_blocks_fid=self.district_blocks_fid, focus_block_logical_id=self.focus_block_logical_id) spinner.pos = self.focus_region_width, 0 spinner.size = '100dp', '34dp' def update_current_fid(*largs): self.current_fid_id = spinner.fid_id spinner.fbind('fid_id', update_current_fid) update_current_fid() self.add_widget(spinner) i = 0 for col in range(cols): for row in range(rows): name = focus_metrics[i] x0 = col * focus_metric_width x1 = x0 + focus_metric_width y0 = row * focus_metric_height y1 = y0 + focus_metric_height self.add_widget(Factory.SizedLabel(text=name, pos=(x0, y0))) with self.canvas: Line(points=[x0, y0, x1, y0, x1, y1, x0, y1], width=2) i += 1 if i >= len(focus_metrics): break if i >= len(focus_metrics): break self.fiducial_graphics = {} self.fiducials_color = {} self.colors = cycle(plt.get_cmap('tab10').colors) self.table_mode = table_mode self.align_mat = align_mat self.district_graphics = [] self.district_metrics_fn = district_metrics_fn self.state_metrics_fn = state_metrics_fn self.screen_offset = screen_offset self.touches = {} with self.canvas.before: PushMatrix() Translate(*screen_offset) with self.canvas.after: PopMatrix() self.show_precincts()
def init_canvas(self): with self.canvas.before: PushMatrix() self.rotation = Rotate(angle=0, origin=self.center) with self.canvas.after: PopMatrix()
def drawObj(self, obj=None): ''' Updates a object if object already on widget. Otherwise it will create a object Override this function to create your own apperance of ojects ''' assert isinstance(obj, mrGraphicsObject) if type(obj) == None: return False # get obj attributes objID = obj.getID() objname = obj.getName() location = self.convertPosition( obj.getLocation() ) color = obj.getColor() wObj = None # draw objects with self.canvas: # set color Color( color[0], color[1], color[2], color[3] ) if type(obj) == mrGraphicsBot: # draw bot assert isinstance(obj, mrGraphicsBot) size = self.convertSize( obj.getSize() ) angle = obj.getAngle() lineW, points, points2, corners = self.getBotDrawData(location, size) print "points", points, points2 p0 = corners[0] p3 = corners[3] # draw object wObj = {'widget': Widget( pos=p0 ), 'label': None} lbl = Label( text=str(objID)+":"+objname, pos=p3 ) lbl.texture_update() tsize = lbl.texture.size lbl.size = (tsize[0], tsize[1]) wObj['label'] = lbl # draw dot with wObj['widget'].canvas.before: PushMatrix() Rotate( angle=angle, axis=(0,0,1), origin=(location[0], location[1], 0) ) with wObj['widget'].canvas.after: PopMatrix() with wObj['widget'].canvas: Color( color[0], color[1], color[2], color[3] ) Line( points=points, width=lineW ) Line( points=points2, width=lineW ) if angle != 0: with wObj['label'].canvas.before: PushMatrix() Rotate( angle=angle, axis=(0,0,1), origin=(location[0], location[1], 0) ) with wObj['label'].canvas.after: PopMatrix() if type(obj) == mrGraphicsRectangle: # draw rectangle assert isinstance(obj, mrGraphicsRectangle) size = self.convertSize( obj.getSize() ) pos = ( location[0]-size[0]/2, location[1]-size[1]/2 ) angle = obj.getAngle() # draw new object wObj = Widget( size=size, pos=pos ) # draw rectangle with wObj.canvas: Color( color[0], color[1], color[2], color[3] ) Rectangle( size=size, pos=pos ) if angle != 0: with wObj.canvas.before: PushMatrix() Rotate( angle=angle, axis=(0,0,1), origin=(location[0], location[1], 0) ) with wObj.canvas.after: PopMatrix() if type(obj) == mrGraphicsLine: #draw line assert isinstance(obj, mrGraphicsLine) points = self.convertPoints( obj.getPoints() ) width = self.convertSize( obj.getWidth() ) # draw new object wObj = Line( points=points, width=width ) if type(obj) == mrGraphicsDot: #draw dot assert isinstance(obj, mrGraphicsDot) radius = self.convertSize( obj.getRadius() ) size = (2*radius, 2*radius) pos = ( location[0]-radius, location[1]-radius ) # draw new object wObj = Ellipse( pos=pos, size=size ) if type(obj) == mrGraphicsCircle: #draw cricle assert isinstance(obj, mrGraphicsCircle) radius = self.convertSize( obj.getRadius() ) width = self.convertSize( obj.getWidth() ) # draw new object wObj = Line( circle=(location[0], location[1], radius), width=width ) if type(obj) == mrGraphicsText: #draw text assert isinstance(obj, mrGraphicsText) text = obj.getText() textcolor = obj.getTextColor() fontsize = obj.getFontSize() angle = obj.getAngle() # draw new object padding = 5 wObj = Label( text=text, pos=location, markup=True, color=textcolor ) if fontsize != None: print "set fontsize", fontsize wObj.font_size = fontsize wObj.texture_update() size = wObj.texture.size wObj.size = (size[0]+2*padding, size[1]+2*padding) with wObj.canvas.before: PushMatrix() Rotate( angle=angle, axis=(0,0,1), origin=(location[0], location[1], 0) ) Color( color[0], color[1], color[2], color[3] ) Rectangle( pos=wObj.pos, size=wObj.size) with wObj.canvas.after: PopMatrix() if type(obj) == mrGraphicsImage: # draw image assert isinstance(obj, mrGraphicsImage) src = obj.getSource() keepRatio = obj.keepRatio() size = self.convertSize( obj.getSize() ) angle = obj.getAngle() if isfile(src): wObj = AsyncImage( source=src, size=size, allow_stretch=True, keep_ratio=keepRatio ) wObj.texture_update() pos = (location[0]-size[0]*0.5, location[1]-size[1]*0.5) wObj.pos = pos size = wObj.size if angle != 0: with wObj.canvas.before: PushMatrix() Rotate( angle=angle, axis=(0,0,1), origin=(location[0], location[1], 0) ) with wObj.canvas.after: PopMatrix() # send update request to canvas self.canvas.ask_update() # return new object return wObj
def draw(self, canvas: Union[RenderContext, InstructionGroup]): canvas.add(PushMatrix()) canvas.add(self.rotate) canvas.add(self.bg_rect) canvas.add(PopMatrix())
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): '''Render text that is displayed in the canvas. The position x, y is given in matplotlib coordinates. A `GraphicsContextKivy` is given to render according to the text properties such as color, size, etc. An angle is given to change the orientation of the text when needed. If the text is a math expression it will be rendered using a MathText parser. ''' if mtext: transform = mtext.get_transform() ax, ay = transform.transform_point(mtext.get_position()) angle_rad = mtext.get_rotation() * np.pi / 180. dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)]) if mtext.get_rotation_mode() == "anchor": # if anchor mode, rotation is undone first v_offset = np.dot(dir_vert, [(x - ax), (y - ay)]) ax = ax + v_offset * dir_vert[0] ay = ay + v_offset * dir_vert[1] w, h, d = self.get_text_width_height_descent(s, prop, ismath) ha, va = mtext.get_ha(), mtext.get_va() if ha == "center": ax -= w / 2 elif ha == "right": ax -= w if va == "top": ay -= h elif va == "center": ay -= h / 2 if mtext.get_rotation_mode() != "anchor": # if not anchor mode, rotation is undone last v_offset = np.dot(dir_vert, [(x - ax), (y - ay)]) ax = ax + v_offset * dir_vert[0] ay = ay + v_offset * dir_vert[1] x, y = ax, ay x += self.widget.x y += self.widget.y if ismath: self.draw_mathtext(gc, x, y, s, prop, angle) else: font = resource_find(prop.get_name() + ".ttf") if font is None: plot_text = CoreLabel(font_size=prop.get_size_in_points()) else: plot_text = CoreLabel(font_size=prop.get_size_in_points(), font_name=prop.get_name()) plot_text.text = six.text_type("{}".format(s)) if prop.get_style() == 'italic': plot_text.italic = True if weight_as_number(prop.get_weight()) > 500: plot_text.bold = True plot_text.refresh() with self.widget.canvas: if isinstance(angle, float): PushMatrix() Rotate(angle=angle, origin=(int(x), int(y))) Rectangle(pos=(int(x), int(y)), texture=plot_text.texture, size=plot_text.texture.size) PopMatrix() else: Rectangle(pos=(int(x), int(y)), texture=plot_text.texture, size=plot_text.texture.size)
def update_tiles(self, dt): # print(self.player.x, self.player.y) self.canvas.clear() viewpane_width = (self.width // self.tile_size) // 2 viewpane_height = (self.height // self.tile_size) // 2 fov_dist = 6 center = (viewpane_width + viewpane_height + 1) // 2 # Find Entities within View Pane entities_to_render = {} entities_to_render = self.find_entities_within_fov( viewpane_width, viewpane_height, fov_dist, dt) # Find Particle Entities within View Pane particles_to_render = {} particles_to_render = self.find_particles_within_fov( viewpane_width, viewpane_height, fov_dist, dt) with self.canvas: Color(1, 1, 1, 1.0) # Render Background Tiles Within for y in range(self.viewpane_center_y + viewpane_height + 1, self.viewpane_center_y - viewpane_height - 1, -1): for x in range(self.viewpane_center_x + viewpane_width + 1, self.viewpane_center_x - viewpane_width - 1, -1): Color(1, 1, 1, 1.0) correct_x = x - self.viewpane_center_x + viewpane_width # normalize to l0 thru map width correct_y = y - self.viewpane_center_y + viewpane_height try: 1 // (abs(y + 1) + y + 1) # check for negative numbers 1 // (abs(x + 1) + x + 1) tile_integer = self.map[y][x] tile_name = self.tile_enum[(floor(tile_integer))] tile_clock_ind = floor(self.map_clock[y][x]) tile_tex = self.data[tile_name][tile_clock_ind] except ZeroDivisionError: tile_tex = self.blank_tex # default to black except IndexError: try: self.map_clock[y][x] = 0 tile_tex = self.data[tile_name][0] except: tile_tex = self.blank_tex # default to black Color(1, 1, 1, 1.0) Rectangle( texture=tile_tex, size=tile_tex.size, pos=((correct_x * self.tile_size) + self.parent.x + self.player_x - self.tile_size, (correct_y * self.tile_size) + self.parent.y + self.player_y - self.tile_size)) # Render Trees try: correct_x = x - self.viewpane_center_x + viewpane_width # normalize to 0 thru map width correct_y = y - self.viewpane_center_y + viewpane_height 1 // (abs(y + 1) + y + 1) 1 // (abs(x + 1) + x + 1) tile_integer = self.tree_map[y][x] tile_name = self.tree_enum[(floor(tile_integer))] tile_tex = self.tree_data[tile_name] # Color(1, 1, 1, randint(0, 255) / 255) # Color(1, 1, 1, randint(200, 255) // 255) Rectangle( texture=tile_tex, size=tile_tex.size, pos=((correct_x * self.tile_size) + self.parent.x + self.player_x - self.tile_size, (correct_y * self.tile_size) + self.parent.y + self.player_y - self.tile_size)) except TypeError: # If "None" is encountered from tree_map array with no object placed # continue pass except IndexError: # If x/y coordinates exceed tree_map array # continue pass except ZeroDivisionError: # Check for any x/y coordinates dips below 0, otherwise will select from end of array # continue pass # Render Particle p = particles_to_render.get((x, y)) if p: p.update(dt) correct_x = ( p.x // self.tile_size ) - self.viewpane_center_x + viewpane_width correct_y = ( p.y // self.tile_size ) - self.viewpane_center_y + viewpane_height PushMatrix() r = Rotate() r.angle = p.angle r.axis = (0, 0, 1) # r = Scale() # r.x = p.scale # r.y = p.scale r.origin = (correct_x * self.tile_size + self.parent.x + self.player_x - (self.tile_size // 2)), ( correct_y * self.tile_size + self.parent.y + self.player_y - (self.tile_size // 2)) Color(1, 1, 0, 1.0) Rectangle( texture=p.texture, size=p.texture.size, pos=((correct_x * self.tile_size + self.parent.x + self.player_x - self.tile_size), (correct_y * self.tile_size + self.parent.y + self.player_y - self.tile_size))) PopMatrix() # Render Entities e = entities_to_render.get((x, y)) if e: entity_tex = self.char_data[e.name] correct_x = (e.x + self.tile_size * viewpane_width) - \ (self.viewpane_center_x * self.tile_size) correct_y = (e.y + self.tile_size * viewpane_height ) - (self.viewpane_center_y * self.tile_size) Rectangle(texture=entity_tex, size=entity_tex.size, pos=((correct_x + self.parent.x + self.player_x - self.tile_size), (correct_y + self.parent.y + self.player_y - self.tile_size))) # FOV Rendering for x in range(self.viewpane_center_x + viewpane_width + 1, self.viewpane_center_x - viewpane_width - 1, -1): for y in range(self.viewpane_center_y + viewpane_height + 1, self.viewpane_center_y - viewpane_height - 1, -1): # FOV/Shadow Texture correct_x = x - self.viewpane_center_x + viewpane_width # normalize to 0 thru map width correct_y = y - self.viewpane_center_y + viewpane_height # Outside FOV dist = self.calculate_distance( correct_x - 1, correct_y - 1, center, center) + 0.05 if dist > fov_dist: Color(0, 0, 0, 0.5) Rectangle( texture=self.blank_tex, size=self.blank_tex.size, pos=((correct_x * self.tile_size) + self.parent.x + self.player_x - self.tile_size, (correct_y * self.tile_size) + self.parent.y + self.player_y - self.tile_size))
def _show_image(config, img, scale=None, translation=None, rotation=None, transform_matrix=None): from kivy.graphics.texture import Texture from kivy.graphics.fbo import Fbo from kivy.graphics import (Mesh, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle, Color) from kivy.graphics.context_instructions import (PushMatrix, PopMatrix, Rotate, Translate, Scale, MatrixInstruction, BindTexture) from kivy.graphics.transformation import Matrix img_fmt = img.get_pixel_format() img_w, img_h = img.get_size() size = config['orig_size'] pos = config['pos'] canvas = config['canvas'] if img_fmt not in ('yuv420p', 'rgba', 'rgb24', 'gray', 'bgr24', 'bgra'): ofmt = get_best_pix_fmt( img_fmt, ('yuv420p', 'rgba', 'rgb24', 'gray', 'bgr24', 'bgra')) swscale = SWScale(iw=img_w, ih=img_h, ifmt=img_fmt, ow=0, oh=0, ofmt=ofmt) img = swscale.scale(img) img_fmt = img.get_pixel_format() kivy_ofmt = { 'yuv420p': 'yuv420p', 'rgba': 'rgba', 'rgb24': 'rgb', 'gray': 'luminance', 'bgr24': 'bgr', 'bgra': 'bgra' }[img_fmt] if kivy_ofmt == 'yuv420p': w2 = int(img_w / 2) h2 = int(img_h / 2) tex_y = Texture.create(size=(img_w, img_h), colorfmt='luminance') tex_u = Texture.create(size=(w2, h2), colorfmt='luminance') tex_v = Texture.create(size=(w2, h2), colorfmt='luminance') with canvas: fbo = Fbo(size=(img_w, img_h)) with fbo: BindTexture(texture=tex_u, index=1) BindTexture(texture=tex_v, index=2) Rectangle(size=fbo.size, texture=tex_y) fbo.shader.fs = CeedDataReader._YUV_RGB_FS fbo['tex_y'] = 0 fbo['tex_u'] = 1 fbo['tex_v'] = 2 tex = fbo.texture dy, du, dv, _ = img.to_memoryview() tex_y.blit_buffer(dy, colorfmt='luminance') tex_u.blit_buffer(du, colorfmt='luminance') tex_v.blit_buffer(dv, colorfmt='luminance') else: tex = Texture.create(size=(img_w, img_h), colorfmt=kivy_ofmt) tex.blit_buffer(img.to_memoryview()[0], colorfmt=kivy_ofmt) tex.flip_vertical() with canvas: StencilPush() Rectangle(pos=pos, size=size) StencilUse() PushMatrix() center = pos[0] + size[0] / 2, pos[1] + size[1] / 2 if rotation: Rotate(angle=rotation, axis=(0, 0, 1), origin=center) if scale: Scale(scale, scale, 1, origin=center) if translation: Translate(*translation) if transform_matrix is not None: mat = Matrix() mat.set(array=transform_matrix) m = MatrixInstruction() m.matrix = mat Rectangle(size=(img_w, img_h), texture=tex, pos=pos) PopMatrix() StencilUnUse() Rectangle(pos=pos, size=size) StencilPop()
def _paint_electrodes_data_setup(self, config, electrode_names, spacing=2, draw_size=(0, 0), draw_size_hint=(1, 1), draw_pos=(0, 0), draw_pos_hint=(None, None), volt_scale=1e-6, time_axis_s=1, volt_axis=100, transform_matrix=None, label_width=70): from kivy.graphics import (Mesh, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle, Color) from kivy.graphics.context_instructions import (PushMatrix, PopMatrix, Scale, MatrixInstruction) from kivy.graphics.transformation import Matrix from kivy.base import EventLoop EventLoop.ensure_window() from kivy.core.text import Label from kivy.metrics import dp, sp n_rows = len(electrode_names) if not n_rows: raise ValueError("There must be at least one electrode specified") n_cols = len(electrode_names[0]) if not n_cols: raise ValueError("There must be at least one electrode specified") if not all((len(row) == n_cols for row in electrode_names)): raise ValueError( "The number of electrodes in all rows must be the same") n_electrodes = sum(map(len, electrode_names)) orig_w, orig_h = config['orig_size'] fbo = config['canvas'] label_height = 45 if label_width else 0 draw_w, draw_h = draw_size draw_hint_w, draw_hint_h = draw_size_hint w = int(draw_w if draw_hint_w is None else orig_w * draw_hint_w) h = int(draw_h if draw_hint_h is None else orig_h * draw_hint_h) draw_x, draw_y = draw_pos draw_hint_x, draw_hint_y = draw_pos_hint x = int(draw_x if draw_hint_x is None else orig_w * draw_hint_x) y = int(draw_y if draw_hint_y is None else orig_h * draw_hint_y) ew = int((w - label_width - max(0, n_cols - 1) * spacing) / n_cols) eh = int((h - label_height - max(0, n_rows - 1) * spacing) / n_rows) with fbo: PushMatrix() # center = x + w / 2., y + h / 2. # if scale: # Scale(scale, scale, 1, origin=center) if transform_matrix is not None: mat = Matrix() mat.set(array=transform_matrix) m = MatrixInstruction() m.matrix = mat positions = [ (0, 0), ] * n_electrodes graphics = [ None, ] * n_electrodes i = 0 electrode_color = 1, 215 / 255, 0, 1 for row, row_names in enumerate(reversed(electrode_names)): ey = y + label_height if row: ey += (eh + spacing) * row for col, name in enumerate(row_names): if name is None: i += 1 continue ex = x + label_width if col: ex += (ew + spacing) * col positions[i] = ex, ey fbo.add(Color(*electrode_color)) fbo.add(StencilPush()) fbo.add(Rectangle(pos=(ex, ey), size=(ew, eh))) fbo.add(StencilUse()) graphics[i] = Mesh(mode='line_strip') fbo.add(graphics[i]) fbo.add(StencilUnUse()) fbo.add(Rectangle(pos=(ex, ey), size=(ew, eh))) fbo.add(StencilPop()) i += 1 if label_width: if not col: fbo.add(Color(1, 1, 1, 1)) label = Label(text=name, font_size=sp(40)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(x, ey + (eh - _h) / 2.), size=label.texture.size) rect.texture = label.texture fbo.add(rect) if not row: fbo.add(Color(1, 1, 1, 1)) label = Label(text=name, font_size=sp(40)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(ex + (ew - _w) / 2., y), size=label.texture.size) rect.texture = label.texture fbo.add(rect) with fbo: Color(1, 1, 1, 1) PopMatrix() electrodes_data = [ None, ] * n_electrodes # y_min, y_max = float('inf'), float('-inf') alignment = np.array(self.electrode_intensity_alignment) # get the frequency from any channel name = None for row_names in electrode_names: for name in row_names: if name is not None: break if name is not None: break freq = self.electrodes_metadata[name]['sampling_frequency'] frame_n = int(1 / config['rate'] * freq) n_t = int(time_axis_s * freq) t_vals = np.arange(n_t) / (n_t - 1) * ew y_scale = (eh / 2) / volt_axis for i, name in enumerate(itertools.chain(*electrode_names)): if name is None: continue offset, scale = self.get_electrode_offset_scale(name) electrodes_data[i] = \ self.electrodes_data[name], offset, scale / volt_scale # y_min = min(np.min(data), y_min) # y_max = max(np.max(data), y_max) new_config = { 'alignment': alignment, 'frame_n': frame_n, 't_vals': t_vals, 'y_scale': y_scale, 'electrodes_data': electrodes_data, 'n_t': n_t, 'positions': positions, 'graphics': graphics, 'eh': eh } return CallableGen(self._paint_electrodes_data(new_config))
def _show_mea_outline(self, config, transform_matrix=None, color=(1, 215 / 255, 0, .2)): from kivy.graphics import (Line, StencilPush, StencilUse, StencilUnUse, StencilPop, Rectangle, Color) from kivy.graphics.context_instructions import (PushMatrix, PopMatrix, Rotate, Translate, Scale, MatrixInstruction, BindTexture) from kivy.graphics.transformation import Matrix from kivy.base import EventLoop EventLoop.ensure_window() from kivy.core.text import Label from kivy.metrics import dp, sp size = config['orig_size'] pos = config['pos'] canvas = config['canvas'] mea_w = max(self.view_controller.mea_num_cols - 1, 0) * \ self.view_controller.mea_pitch mea_h = max(self.view_controller.mea_num_rows - 1, 0) * \ self.view_controller.mea_pitch last_col = "ABCDEFGHJKLMNOPQRSTUVWXYZ"[ self.view_controller.mea_num_cols - 1] with canvas: StencilPush() Rectangle(pos=pos, size=size) StencilUse() PushMatrix() if transform_matrix is not None: mat = Matrix() mat.set(array=transform_matrix) m = MatrixInstruction() m.matrix = mat Color(*color) Line(points=[0, 0, mea_w, 0, mea_w, mea_h, 0, mea_h], close=True) label = Label(text='A1', font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(mea_w, mea_h - _h / 2.), size=label.texture.size) rect.texture = label.texture label = Label(text='A{}'.format(self.view_controller.mea_num_rows), font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(-_w, mea_h - _h / 2.), size=label.texture.size) rect.texture = label.texture label = Label(text='{}1'.format(last_col), font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(mea_w, -_h / 2.), size=label.texture.size) rect.texture = label.texture label = Label(text='{}{}'.format( last_col, self.view_controller.mea_num_rows), font_size=sp(12)) label.refresh() _w, _h = label.texture.size rect = Rectangle(pos=(-_w, -_h / 2.), size=label.texture.size) rect.texture = label.texture PopMatrix() StencilUnUse() Rectangle(pos=pos, size=size) StencilPop()