Example #1
2
def restore_poly_from_path_str(path_str):
    """
    restores a list of polygons from a SVG path string
    """
    contours = path_str.split('Z')  # last contour may be empty
    from Polygon import Polygon as Poly
    poly = Poly()
    for c_str in contours:
        if c_str.strip() != "":
            pts_str = c_str.strip()[1:].split("L")
            pts = []
            for pt_str in pts_str:
                x, y = map(float, pt_str.split(','))
                pts.append((x, y))
            poly.addContour(pts, is_clockwise(pts))
    return poly
Example #2
1
def line(pos=(0,0), np=2, rotate=0.0, scale=1.0, xscale=1.0, yscale=1.0,
           thickness=None, start=(0,0), end=(0,1), path=False):
        v = vis.vector((end[0]-start[0]), (end[1]-start[1]))
        if thickness is None:
            thickness = 0.01*vis.mag(v)
        dv = thickness*vis.norm(vis.vector(0,0,1).cross(v))
        dx = dv.x
        dy = dv.y
        cp = [] # outer line
        cpi = [] # inner line
        vline = (vis.vector(end)-vis.vector(start)).norm()
        mline = vis.mag(vis.vector(end)-vis.vector(start))
        for i in range(np):
            x = start[0] + (vline*i)[0]/float(np-1)*mline
            y = start[1] + (vline*i)[1]/float(np-1)*mline
            cp.append( (x+pos[0],y+pos[1]) )
            cpi.append( (x+pos[0]+dx,y+pos[1]+dy) )
        if not path:
                cpi.reverse()
                for p in cpi:
                    cp.append(p)
                cp.append(cp[0])
        if rotate != 0.0: cp = rotatecp(cp, pos, rotate)
        if scale != 1.0: xscale = yscale = scale
        pp = Polygon(cp)
        if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
        if not path:
                return pp
        else:
                return [cp]
Example #3
0
def trframe(pos=(0,0), width=2.0, height=1.0, top=None, thickness=None, rotate=0.0,
              roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0):
        if top == None: top = width/2.0
        if thickness == Default or thickness == None: thickness = min(height,top)*0.2
        else: thickness = min(height,top)*thickness*2
        fsqr = trapezoid(pos=pos, width=width, height=height, top=top)
        angle = atan((width-top)/2.0/height)
        db = (thickness)/cos(angle)
        sqr1 = trapezoid(pos=pos, width=(width-db-thickness*tan(angle)),
                                height=height-thickness, top=top-(db-thickness*tan(angle)))
        pp = fsqr - sqr1
        if rotate != 0.0: pp.rotate(rotate)
        if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
        if roundness > 0:
                cp0 = pp.contour(0)
                cp0.append(cp0[0])
                cp0 = roundc(cp0, roundness=roundness, invert=invert)
                cp1 = pp.contour(1)
                cp1.append(cp1[0])
                cp1 = roundc(cp1, roundness=roundness, invert=invert)
                p1 = Polygon(cp0)
                p2 = Polygon(cp1)
                pp = p2-p1
                return pp
        else: return pp
Example #4
0
def nframe(pos=(0,0), length=1.0, np=3, thickness=None, rotate=0.0,
              roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0):
        if thickness == Default or thickness == None: thickness = length*0.2
        else: thickness = length*thickness*2
        fsqr = ngon(pos=pos, np=np, length=length)
        nga = (np-2)*pi/np
        angle = (pi/2 - nga)
        length2=length-thickness*cos(angle)
        csa = cos(angle)
        sqr1 = ngon(pos=pos, np=np, length=length-thickness/csa*2-thickness*tan(angle)*2)
        pp = fsqr - sqr1
        if rotate != 0.0: pp.rotate(rotate)
        if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
        if roundness > 0:
                cp0 = pp.contour(0)
                cp0.append(cp0[0])
                cp0 = roundc(cp0, roundness=roundness, invert=invert)
                cp1 = pp.contour(1)
                cp1.append(cp1[0])
                cp1 = roundc(cp1, roundness=roundness, invert=invert)
                p1 = Polygon(cp0)
                p2 = Polygon(cp1)
                pp = p2-p1
                return pp
        else: return pp
Example #5
0
def get_pyramid_polygons():
    polygons = []
    # front
    face = get_triangle_points()
    transform = get_shift_matrix(0, 0, 1).dot(get_rot_x_matrix(-math.pi / 4))
    face = face.dot(transform)
    face = face.dot(get_shift_matrix(0, 0, 1))
    polygons.append(Polygon(face))
    # back
    face = get_triangle_points()
    face = face.dot(get_rot_x_matrix(math.pi / 4))
    face = face.dot(get_shift_matrix(0, 0, -1))
    polygons.append(Polygon(face))
    # left
    face = get_triangle_points()
    face = face.dot(get_rot_x_matrix(-math.pi / 4))
    face = face.dot(get_rot_y_matrix(-math.pi / 2))
    face = face.dot(get_shift_matrix(1, 0, 0))
    polygons.append(Polygon(face))
    # right
    face = get_triangle_points()
    face = face.dot(get_rot_x_matrix(-math.pi / 4))
    face = face.dot(get_rot_y_matrix(math.pi / 2))
    face = face.dot(get_shift_matrix(-1, 0, 0))
    polygons.append(face)
    return polygons
Example #6
0
def rectangle(pos=(0,0), width=1.0, height=None, rotate=0.0, thickness=0, 
              roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0):
        if height is None: height = width
        
        if thickness == 0:
            p0 = (pos[0]+width/2.0, pos[1]-height/2.0)
            p1 = (pos[0]+width/2.0, pos[1]+height/2.0)
            p2 = (pos[0]-width/2.0, pos[1]+height/2.0)
            p3 = (pos[0]-width/2.0, pos[1]-height/2.0)
            p4 = (pos[0]+width/2.0, pos[1]-height/2.0)

            cp = [p0, p1, p2, p3, p4]
            if rotate != 0.0: cp = rotatecp(cp, pos, rotate)
            if scale != 1.0: xscale = yscale = scale
            pp = Polygon(cp)
            if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
            if roundness > 0:
                cp = roundc(pp.contour(0), roundness=roundness, invert=invert)
                return Polygon(cp)
            else: return pp
        else:
            pp = rframe(pos=pos, width=width, height=height, thickness=thickness,
                       rotate=rotate, roundness=roundness, invert=invert,
                       scale=scale, xscale=xscale, yscale=yscale)
            return pp
Example #7
0
def rackGear(pos=(0,0), n=30, radius=5., phi=20., addendum=0.4, dedendum=0.5,
         fradius=0.1, rotate=0, scale=1.0, length=10*pi, res=1, bevel=0.05, depth=(0.4+0.6+0.1)):
        tooth = RackOutline(n, res, phi, radius, addendum, dedendum,
                        fradius, bevel)

        toothl = tooth[0][1] - tooth[-1][1]

        ntooth = int(length/toothl)
        flength = ntooth * toothl

        gear = []
        for i in range(0, ntooth):
            ntooth = []
            for (x, y) in tooth:
                nx = x + pos[0]
                ny = -i*toothl + y + pos[1]
                ntooth.append((nx,ny))
            gear.extend(ntooth)
        gear.append((gear[-1][0]-depth,gear[-1][1]))
        gear.append((gear[0][0]-depth,gear[0][1]))
        gear.append(gear[0])
        pp =  Polygon(gear)
        pp.shift(-pp.center()[0],-pp.center()[1])
        if rotate != 0.0: pp.rotate(rotate)
        if scale != 1.0 : pp.scale(scale,scale)
        return pp
Example #8
0
def gear(pos=(0,0), n=20, radius=5, phi=20, addendum=0.4, dedendum=0.5,
         fradius=0.1, rotate=0, scale=1.0, internal=False, res=1, bevel=0):
        tooth = ToothOutline(n, res, phi, radius, addendum, dedendum,
                        fradius, bevel=0.0)
        if internal:
                itooth = []
                for p in tooth:
                        px = p[0]
                        py = p[1]
                        driro = sqrt(px*px +py*py) - radius
                        ir = radius - driro
                        ro = radius + driro
                        ix = (ir/ro)*px
                        iy = (ir/ro)*py
                        itooth.append((ix,iy))

                tooth = itooth
        gear = []
        for i in range(0, n):
            rotan = -i*2*pi/n
            rtooth = []
            for (x, y) in tooth:
                rx = x*cos(rotan) - y*sin(rotan) + pos[0]
                ry = x*sin(rotan) + y*cos(rotan) + pos[1]
                rtooth.append((rx,ry))
            gear.extend(rtooth)
        #gear.append(gear[0])
        pp =  Polygon(gear)
        if rotate != 0.0: pp.rotate(rotate)
        if scale != 1.0 : pp.scale(scale,scale)
        return pp
Example #9
0
def test_circle_overlaps_poly(circle_center, circle_radius, poly_points):
	# Start with a cheap points-in-circle test
	circle_radius2 = circle_radius * circle_radius
	for i in range(len(poly_points)):
		xdiff = poly_points[i][0] - circle_center[0]
		ydiff = poly_points[i][1] - circle_center[1]
		if (xdiff*xdiff + ydiff*ydiff) <= circle_radius2:
			return True

	# Now try a bounding-rectangle test
	min_x = min(poly_points, key=lambda p: p[0])[0]
	max_x = max(poly_points, key=lambda p: p[0])[0]
	min_y = min(poly_points, key=lambda p: p[1])[1]
	max_y = max(poly_points, key=lambda p: p[1])[1]
	rect_pos = [min_x, min_y]
	rect_size = np.subtract((max_x, max_y), rect_pos)
	if not test_circle_overlaps_rect(circle_center, circle_radius, rect_pos, rect_size):
		return False

	# Brute-force all the possible line collsions
	for i in range(len(poly_points)-1):
		line = [poly_points[i], poly_points[i+1]];
		inters = circle_line_intersection(circle_center, circle_radius, line);
		if inters is not None and 0 < len(inters):
			return True

	# The only other way to collide is if the circle is completely inside
	# the polygon
	polyob = Polygon(poly_points)
	return polyob.contains_point(circle_center)
Example #10
0
def shape_center(shape):
	"""
	computes the center of gravity of a shapefile multi-polygon
	"""
	from Polygon import Polygon
	parts = shape.parts[:]
	parts.append(len(shape.points))
	
	# check for countries that cross the 180° longitude
	
	far_east = False
	far_west = False
	
	for i in range(len(parts)-1):
		pts = shape.points[parts[i]:parts[i+1]]
		if len(pts) == 0: continue
		if pts[0][0] < -90:
			far_west = True
		if pts[0][0] > 90:
			far_east = True
	
	poly = Polygon()
	for i in range(len(parts)-1):
		pts = shape.points[parts[i]:parts[i+1]]
		if far_east and far_west:
			# correct points
			for j in range(len(pts)):
				if pts[j][0] < 0: pts[j][0] += 360
		poly.addContour(pts)
	return poly.center()
Example #11
0
    def tile(tile_count, tile_set, radial_placement=True):
        node_set = NodeSet(100)
        edge_set = EdgeSet(1000, 1000, node_set)
        polygon_set = PolygonSet(tile_set, node_set, edge_set)

        InitPolygonType = choice(tile_set)
        polygons = [Polygon.create(InitPolygonType, polygon_set)]

        possibilities = [(PolygonType, i) for PolygonType in tile_set
                         for i in range(len(PolygonType.angles))]

        for _ in range(tile_count - len(polygons)):
            cur_edge = polygon_set.get_random_open_edge()
            #possible to switch next line with generator function?

            shuffle(possibilities)
            for possibility in possibilities:
                NewPolygonType, start_index = possibility
                valid_new_edges = Polygon.place(NewPolygonType, cur_edge,
                                                start_index, polygon_set)
                if valid_new_edges != None:
                    polygons.append(
                        NewPolygonType(valid_new_edges, polygon_set))
                    break

            #polygon_set.remove_polygon(edge=cur_edge)

        return polygons
Example #12
0
    def __init__(self, world, chunk_pos):
        self.world = world
        self.pos = (chunk_pos[0] * 51.2, chunk_pos[1] * 51.2)
        self.chunk_pos = (chunk_pos[0] % 32, chunk_pos[1])
        self.texture = None
        self.polygon = None
        self.body = None
        self.entities = []
        self.things_to_blit = []

        texture_filename = "data/world/%i_%i.tga" % self.chunk_pos
        if os.path.exists(texture_filename):
            self.texture = pygame.image.load(texture_filename)
            self.texture.set_colorkey((255, 0, 255))
        elif chunk_pos[1] <= 1:
            self.texture = Chunk.underground_texture

        data_filename = "data/world/%i_%i.dat" % self.chunk_pos
        if os.path.exists(data_filename):
            with open(data_filename) as fin:
                self.polygon, self.entities = pickle.load(fin)
        elif chunk_pos[1] <= 1:
            self.polygon = Polygon(
                ((-25.6, -25.6), (-25.6, 25.6), (25.6, 25.6), (25.6, -25.6)))

        self.load_body()
Example #13
0
    def __init__(self, score, time):
        "Initialises resources and start level"

        self.background = pygame.image.load("sprites/sky.jpg")
        self.background.convert()  #for blitting more faster

        self.screen = Constants.SCREEN
        self.score = score
        self.display_items = pygame.sprite.Group()
        self.timeclock = GameTime((0.05, 0.05), time)
        self.display_items.add(self.timeclock, self.score)

        self.time_speed = pygame.time.Clock()
        self.time = 0.0

        self.quit = False
        self.pause = False
        self.start = False
        self.completed = False
        self.gameover = False
        self.message = None

        self.polygon = Polygon(self)
        self.event_manager = EventManager(self)
        self.on_enter()
Example #14
0
    def test_7_distance(self):
        """Test distance after various operations"""
        polygon = Polygon()

        # Test initial distance
        polygon.insert((0, 0), 0)
        self.assertTrue(polygon[0].distance_to_next == 0)

        # Test distance after adding after
        polygon.insert((3, 4), 1)
        self.assertTrue(polygon[0].distance_to_next == 5)
        self.assertTrue(polygon[1].distance_to_next == 5)

        # Test distance after adding before
        polygon.insert((3, -4), 1)
        self.assertTrue(polygon[0].distance_to_next == 5)
        self.assertTrue(polygon[1].distance_to_next == 8)

        # Test distance after []=
        polygon[1] = (1, 1)
        self.assertTrue(polygon[0].distance_to_next == math.sqrt(2))
        self.assertTrue(polygon[1].distance_to_next == math.sqrt(13))

        # Test distance after remove
        polygon.remove(1)
        self.assertTrue(polygon[0].distance_to_next == 5)
Example #15
0
    def __init__(self,
                 vertices,
                 color=(255, 255, 255),
                 velocity=(0, 0),
                 angular_velocity=0,
                 colors=None):
        if isinstance(vertices, Polygon):
            self.poly = vertices
        else:
            self.poly = Polygon(vertices)

        self.colors = colors
        self._color = 'primary'
        if colors:
            self.color = color

        else:
            self.colors = {'primary': color}

        self.velocity = np.asarray(velocity)
        self.angular_velocity = angular_velocity

        # Construct vertex_list.
        self._vertex_list = self._get_vertex_list()
        self.enabled = True
def support(
    p
):  # false if not satisfies some the next conditions on the parameter spaces
    [x, spline, alpha, elast] = p

    if elast > 60:
        return False

    if len(spline) == 0:
        return False

    if (alpha <= 0):
        return False
    x_sp = spline

    if (x_sp > 0.78).any() | (x_sp < 0.0).any():
        return False
    Q = Polygon(x_sp)

    if Q.is_valid_polygon() == False:
        return False

    area_convex = ConvexHull(x.T).volume
    if (Q.area() / area_convex) < 0.8:
        return False

    return is_valid_spline_JA(x_sp, h)
Example #17
0
def ngon(pos=(0,0), np=3, length=None, radius=1.0, rotate=0.0, thickness=0,
         roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0):
        cp = [] 
        if np < 3:
                raise AttributeError("number of sides can not be less than 3")
                return None

        angle = 2*pi/np
        if length != None: radius = (length/2.0)/(sin(angle/2))    
        else: length = radius*(sin(angle/2))*2
        if thickness == 0:
            seg = 2.0*pi/np
            angle = rotate
            for i in range(np):
                x = radius*cos(angle) + pos[0]
                y = radius*sin(angle) + pos[1]
                cp.append((x,y))
                angle += seg
            cp.append(cp[0])
            if scale != 1.0: xscale = yscale = scale
            pp = Polygon(cp)
            if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
            if roundness > 0:
                    cp = roundc(pp.contour(0), roundness=roundness, invert=invert)
                    return Polygon(cp)
            else: return pp
        else:
            pp = nframe(pos=pos, length=length, thickness=thickness, roundness=roundness,
                        invert=invert, rotate=rotate, np=np)
            return pp
Example #18
0
def ellipse(pos=(0,0), width=1.0, height=None, np=32, rotate=0.0, thickness=None,
            scale=1.0, xscale=1.0, yscale=1.0):
        if height == None: height = 0.5*width
        if thickness == 0 or thickness == None:
            cp = []
            seg = 2.0*pi/np
            angle = 0
            radius=0.5
            lf = width/2.0
            hf = height/2.0
            for i in range(np):
                x = cos(angle)*lf + pos[0]
                y = sin(angle)*hf + pos[1]
                cp.append((x,y))
                angle += seg
            cp.append(cp[0])
            if rotate != 0.0: cp = rotatecp(cp, pos, rotate)
            if scale != 1.0: xscale = yscale = scale
            pp = Polygon(cp)
            if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
            return pp
        else:
            pp = ering(pos=pos, width=width, height=height, np=np, rotate=rotate,
                  thickness=thickness)
            return pp
Example #19
0
def arc(pos=(0,0), radius=0.5, np=32, rotate=0.0, scale=1.0, xscale=1.0, yscale=1.0,
           thickness=None, angle1=0.0, angle2=pi, path=False):
        if thickness is None:
            thickness = 0.01*radius
        cp = []  # outer arc
        cpi = [] # inner arc
        seg = 2.0*pi/np
        nseg = int(abs((angle2-angle1))/seg)+1
        seg = (angle2-angle1)/nseg
        for i in range(nseg+1):
            x = cos(angle1+i*seg)
            y = sin(angle1+i*seg)
            cp.append( (radius*x+pos[0],radius*y+pos[1]) )
            cpi.append( ((radius-thickness)*x+pos[0],(radius-thickness)*y+pos[1]) )
        if not path:
                cpi.reverse()
                for p in cpi:
                    cp.append(p)
                cp.append(cp[0])
        if rotate != 0.0: cp = rotatecp(cp, pos, rotate)
        if scale != 1.0: xscale = yscale = scale
        pp = Polygon(cp)
        if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
        if not path:
                return pp
        else:
                return [cp]
Example #20
0
    def test_3_address_non_existing_point(self):
        """Test addressing non existing Point."""
        polygon = Polygon()
        with self.assertRaises(Exception):
            polygon[0] = (1, 3)

        # Cannot remove an item
        with self.assertRaises(Exception):
            polygon.remove(0)
Example #21
0
 def reset_everything(self):
     self.canvas.delete('all')
     self.operation_flag = 0
     self.reset_last_coord()
     self.reset_first_coord()
     self.main_polygon = Polygon()
     self.clipping_polygon = Polygon()
     self.vertex_list = None
     self.clipping = None
Example #22
0
def obliq_proj(event):
    clean()
    polygon = Polygon()
    matrix = polygon.obliq_proj()
    plot_all_faces(polygon.faces)
    plot_all_vertices(polygon.vertices)
    matrix_ax.table(cellText=matrix, colLabels=matrix_collabel, loc='center')
    tables_fig.canvas.draw()
    plt.draw()
Example #23
0
 def test_4_insert(self):
     """Test insertion"""
     polygon = Polygon()
     polygon.insert((1, 2), 0)
     self.assertTrue(len(polygon) == 1)
     self.assertTrue(polygon[0] == (1, 2))
     self.assertTrue(polygon[0].distance_to_next == 0)
     self.assertTrue(polygon[0].angle == 0)
     self.assertTrue(polygon.get_area() == 0)
Example #24
0
 def test_5_addressing(self):
     """Test addressing"""
     polygon = Polygon()
     polygon.insert((1, 2), 0)
     polygon[0] = (8, 9)
     self.assertTrue(polygon[-1] == (8, 9))
     self.assertTrue(polygon[0] == (8, 9))
     self.assertTrue(polygon[0].distance_to_next == 0)
     self.assertTrue(polygon[0].angle == 0)
     self.assertTrue(polygon.get_area() == 0)
Example #25
0
def pointlist(pos=[], rotate=0.0, roundness=0.0, invert=False,
              scale=1.0, xscale=1.0, yscale=1.0, path=False):
    # pos may be either a list of points or a Polygon object
    try:
        points = pos.contour(0)
        if len(pos) > 1:
            raise AttributeError("pointlist can deal with only a single contour.")
    except:
        points = pos[:]
    closed = (points[-1] == points[0])
    if not closed:
        points.append(points[0])
    pp = Polygon(points)
    if len(pp) and rotate != 0.0: pp.rotate(rotate)
    if scale != 1.0: xscale = yscale = scale
    if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
    if roundness > 0:
        cp = roundc(pp.contour(0), roundness=roundness, invert=invert)
        pp = Polygon(cp)
    if path:
        if closed:
            return list(pp)
        else:
            return list(pp)[:-1]
    else:
        return pp
Example #26
0
def find_inside_point(p: Polygon.Polygon, i: int):
    # random search
    xmin, xmax, ymin, ymax = p.boundingBox(i)
    for _ in range(1000):
        x = random.random() * (xmax - xmin) + xmin
        y = random.random() * (ymax - ymin) + ymin

        if p.isInside(x, y, i):
            return x, y

    raise Exception("Couldn't find interior point")
Example #27
0
 def center(self):
     ret = [0, 0]
     if self.type() == 'MultiPolygon':
         p = Polygon(self.coordinates()[0][0])
         ret = list(p.center())
     else:
         ret = self.coordinates()
         
     c = transform_to_4326(self.crs_code(), ret[0], ret[1])
     
     return [c[0], c[1]]
Example #28
0
def common_area(x0, y0, x1, y1):
    nb, _ = x0.shape
    cost = empty((nb))
    for i in range(nb):
        x0_, x1_ = x0[i], x1[i]
        if abs(x0_[0] - x1_[0]) > 180:
            x1_ = (x1[i] - (x0_[0] - 180)) % 360 + x0_[0] - 180
        p0 = Polygon(create_vertice(x0_, y0[i]))
        p1 = Polygon(create_vertice(x1_, y1[i]))
        cost[i] = (p0 & p1).area() / (p0 + p1).area()
    return cost
Example #29
0
def polygon_center(polygon):
	"""
	computes the center of gravity of a gisutils.Polygon
	"""
	from Polygon import Polygon as Poly
	pts = []
	for pt in polygon.points:
		pts.append((pt.x, pt.y))
	poly = Poly(pts)
	c = poly.center()
	return Point(c[0], c[1])
Example #30
0
    def overlaps_segment(self, other):
        """
        Determines whether the query segment overlaps with this
        :py:class:`TriSegment`

        :param other: query :py:class:`TriSegment`

        :return: ``True`` iff the query segment overlaps with this segment
        """
        p_self = Polygon(np.dot(self.xyz_points, self.projection_plane.T))
        p_other = Polygon(np.dot(other.xyz_points, self.projection_plane.T))
        return ((p_self & p_other).area() > 0)
Example #31
0
 def addTestPolygons(self):
     from Polygon import Polygon
     self.robot = Polygon([(-1, 0), (0, -1), (1, 0), (0, 1)])
     #self.robot = Polygon(generateCircle(100, (-4, -4)))
     self.polygons = [
         #Polygon(generateCircle(100, (4, 4))),
         #Polygon([(2, 1), (5, 1), (5, 4), (2, 4)]),
         #Polygon([(-1, 3), (1, 0), (4, 2), (2, 4)]),
         #Polygon([(3, -4), (7, -3), (5.5, -2)]),
         #Polygon([(3, 4), (6, 3), (5, 2)]),
     ]
     self.buildVisibilityMap()
Example #32
0
 def calcQueryBBox(self, bbox):
     print("new bbox")
     ymin = bbox[1] - self.getRoutingBBoxMargin()
     xmin = bbox[0] - self.getRoutingBBoxMargin()
     ymax = bbox[3] + self.getRoutingBBoxMargin()
     xmax = bbox[2] + self.getRoutingBBoxMargin()
     bboxNew = [xmin, ymin, xmax, ymax]
     self.lastBBoxCPolygon = Polygon([(bboxNew[0], bboxNew[3]),
                                      (bboxNew[2], bboxNew[3]),
                                      (bboxNew[2], bboxNew[1]),
                                      (bboxNew[0], bboxNew[1])])
     self.lastBBox = bboxNew
Example #33
0
 def _maxeffpolygon(c):
     max_ratio = 0
     radius = 5
     for i in range(3, c + 1):
         pol = Polygon(i, radius)
         #print(pol.area())
         r = pol.area() / pol.perimeter()
         #print(r)
         if r > max_ratio:
             max_ratio = r
             side_len = i
     return f'Polygon having max efficiency is having side:{side_len} and the ratio is:{max_ratio:0.3f}\n'
Example #34
0
    def test_2_point_is_valid(self):
        """Test point's validation. Point MUST be a 2 dimensional tuple (x,y)"""
        polygon = Polygon()
        with self.assertRaises(Exception):
            polygon.insert((1, ), 0)

        with self.assertRaises(Exception):
            polygon.insert(1, 0)

        with self.assertRaises(Exception):
            polygon.insert((1, "2"), 0)

        with self.assertRaises(Exception):
            polygon.insert(("1", 2), 0)
Example #35
0
    def __init__(self, world, chunk_pos):
        self.world = world
        self.pos = (chunk_pos[0] * 51.2, chunk_pos[1] * 51.2)
        self.chunk_pos = (chunk_pos[0] % 32, chunk_pos[1])
        self.texture = None
        self.polygon = None
        self.body = None
        self.entities = []
        self.things_to_blit = []

        texture_filename = "data/world/%i_%i.tga" % self.chunk_pos
        if os.path.exists(texture_filename):
            self.texture = pygame.image.load(texture_filename)
            self.texture.set_colorkey((255, 0, 255))
        elif chunk_pos[1] <= 1:
            self.texture = Chunk.underground_texture

        data_filename = "data/world/%i_%i.dat" % self.chunk_pos
        if os.path.exists(data_filename):
            with open(data_filename) as fin:
                self.polygon, self.entities = pickle.load(fin)
        elif chunk_pos[1] <= 1:
            self.polygon = Polygon((
                (-25.6, -25.6), 
                (-25.6, 25.6), 
                (25.6, 25.6), 
                (25.6, -25.6) 
            ))

        self.load_body()
Example #36
0
def build_polygons(cell_indices, A0):
	polys = []
	for i,indices in enumerate(cell_indices):
		theta = rand_angle()
		poly = Polygon(i, indices, A0, theta)
		polys.append(poly)
	return polys
Example #37
0
def restore_poly_from_path_str(path_str):
    """
    restores a list of polygons from a SVG path string
    """
    contours = path_str.split('Z')  # last contour may be empty
    from Polygon import Polygon as Poly
    poly = Poly()
    for c_str in contours:
        if c_str.strip() != "":
            pts_str = c_str.strip()[1:].split("L")
            pts = []
            for pt_str in pts_str:
                x, y = map(float, pt_str.split(','))
                pts.append((x, y))
            poly.addContour(pts, is_clockwise(pts))
    return poly
Example #38
0
	def __init__(self,score,time):
		"Initialises resources and start level"
		
		self.background=pygame.image.load("sprites/sky.jpg")
		self.background.convert() #for blitting more faster
		
		self.screen=Constants.SCREEN
		self.score = score
		self.display_items = pygame.sprite.Group()
		self.timeclock = GameTime((0.05,0.05),time)		
		self.display_items.add(self.timeclock,self.score)
		
		self.time_speed=pygame.time.Clock()
		self.time=0.0
		
		self.quit = False
		self.pause = False
		self.start = False
		self.completed = False
		self.gameover = False
		self.message = None
		
		self.polygon=Polygon(self)
		self.event_manager = EventManager(self)
		self.on_enter()
def _create_map_1(env):
    #obs_movement = MovementPattern.StaticMovement((0,0))
    #obs = DynamicObstacle(obs_movement)
    #obs.fillcolor = (0x55, 0x55, 0x55)
    #obs.shape = 4
    #obs.polygon = Polygon([
    #	(640, 80),
    #	(640, 480),
    #	(445, 450),
    #	(408, 300),
    #	(408, 165),
    #	(460, 108),
    #	(490, 104),
    #	(490, 91),
    #	(640, 80),
    #]);
    with open('obs2.json') as f:
        obslist = json.load(f)

    for obs in obslist:
        obs_movement = MovementPattern.StaticMovement((0, 0))
        if obs['type'] == 'circle':
            obs_movement = MovementPattern.StaticMovement(obs['center'])
            obs2 = DynamicObstacle(obs_movement)
            obs2.shape = 1
            obs2.radius = obs['radius']
            obs2.fillcolor = (0x55, 0x55, 0x55)
            env.static_obstacles.append(obs2)
            continue
        polygon = Polygon(np.array(obs['points']))
        obs2 = DynamicObstacle(obs_movement)
        obs2.shape = 4
        obs2.polygon = polygon
        obs2.fillcolor = (0x55, 0x55, 0x55)
        env.static_obstacles.append(obs2)
 def __init__( self , polygons = None ):
     if polygons is None:
         self._polygons = [ Polygon.rand_triangle( IMG_WIDTH , IMG_HEIGHT ) for _ in range( 0 , P ) ]
     else:
         self._polygons = polygons
     self._fitness = -1
     self._pixelArray = None
     pass
Example #41
0
File: Actor.py Project: ducino/dig
 def updateLocation(self, newLocation):
     self.previousLocation = self.location
     self.location = newLocation
     self.bbox = BoundingBox(self.location.x-self.width/2, self.location.y-self.height/2,
                             self.location.x+self.width/2, self.location.y+self.height/2)
     self.polygon = Polygon.createBoundingBoxPolygon(Vector(self.location.x-self.width/2, self.location.y-self.height/2),
                                             Vector(self.location.x+self.width/2, self.location.y+self.height/2))
     self.polygon.convex = True        
def fetch_grid((i, j)):
    """on demand generation of empty grid squares."""
    (i, j) = unwrap((i, j))
    if (i, j) not in grid:
        xloc = i * grid_spacing
        yloc = j * grid_spacing
        r = Polygon(
            [
                (xloc, yloc),
                (xloc + grid_spacing, yloc),
                (xloc + grid_spacing, yloc + grid_spacing),
                (xloc, yloc + grid_spacing),
            ]
        )
        p = sample.sample(r)
        t = random.expovariate(r.area())
        grid[i, j] = (p, t, r)
    return grid[(i, j)]
Example #43
0
    def apply_contours(self, contours):
        """
        constructs a Polygon from contours
        """
        self.contours = contours
        from Polygon import Polygon as GPCPoly
        poly = GPCPoly()
        skip = 0
        for pts_ in contours:
            pts = []
            for pt in pts_:
                if 'deleted' in pt and pt.deleted is True:
                    skip += 1
                    continue
                pts.append((pt[0], pt[1]))
            ishole = utils.is_clockwise(pts)

            if len(pts) > 2:
                poly.addContour(pts, ishole)
        self.poly = poly
Example #44
0
def circle(pos=(0,0), radius=0.5, np=32, scale=1.0, xscale=1.0, yscale=1.0,
           thickness=0):
        if thickness == 0:
            cp = []
            seg = 2.0*pi/np
            for i in range(np):
                angle = i*seg
                x = radius*cos(angle) + pos[0]
                y = radius*sin(angle) + pos[1]
                cp.append((x,y))
            cp.append(cp[0])
            if scale != 1.0: xscale = yscale = scale
            pp = Polygon(cp)
            if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
            return pp
        else:
            if thickness == Default: thickness = radius*0.2
            pp = ring(pos=pos, radius=radius, np=np, scale=scale,
                      iradius=(radius-thickness), xscale=xscale, yscale=yscale)
            return pp
Example #45
0
def star(pos=(0,0), radius=1.0, n=5, iradius=None, rotate=0.0, thickness=0.0,
         roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0):
    if iradius == None: iradius = radius*0.5
    if thickness == 0.0:
        pstar = Star(radius=radius, center=pos, beams=n, iradius=iradius)
        cp = pstar[0]
        cp.append(cp[0])
        cp.reverse() # Polygon Star goes around clockwise, so reverse to go CCW
        cp = rotatecp(cp, pos, rotate)
        if scale != 1.0: xscale = yscale = scale
        pp = Polygon(cp)
        if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
        if roundness > 0:
            cp = roundc(pp.contour(0), roundness=roundness, invert=invert)
            return Polygon(cp)
        else: return pp
    else:
        pp = sframe(pos=pos, radius=radius, iradius=iradius, rotate=rotate,
                    thickness=thickness, roundness=roundness, invert=invert,
                    scale=scale, xscale=xscale, yscale=yscale, n=n)
        return pp
Example #46
0
def cross(pos=(0,0), width=1.0, thickness=0.2, rotate=0.0,
              roundness=0.0, invert=False, scale=1.0, xscale=1.0, yscale=1.0):

        fsqr = rectangle(pos=pos, width=width)
        sqr1 = rectangle(pos=(pos[0]-(width+thickness)/4.0,
                                     pos[1]+(width+thickness)/4.0), width=(width-thickness)/2.0)
        sqr2 = rectangle(pos=(pos[0]+(width+thickness)/4.0,
                                     pos[1]+(width+thickness)/4.0), width=(width-thickness)/2.0)
        sqr3 = rectangle(pos=(pos[0]+(width+thickness)/4.0,
                                     pos[1]-(width+thickness)/4.0), width=(width-thickness)/2.0)
        sqr4 = rectangle(pos=(pos[0]-(width+thickness)/4.0,
                                     pos[1]-(width+thickness)/4.0), width=(width-thickness)/2.0)
        poly = fsqr - sqr1 -sqr2 -sqr3 -sqr4
        cp = poly.contour(0)
        cp.append(cp[0])
        if rotate != 0.0: cp = rotatecp(cp, pos, rotate)
        pp = Polygon(cp)
        if xscale != 1.0 or yscale != 1.0: pp.scale(xscale,yscale)
        if roundness > 0:
                cp = roundc(pp.contour(0), roundness=roundness, invert=invert)
                return Polygon(cp)
        else: return pp
Example #47
0
def generate_polygon(coords, scale):
    """
    Generate a polygon that encompasses a set of grid coordinates.

    :param coords: List of coordinates to draw polygon around
    :param scale: Area around each grid square (1/scale in degrees is area of each point)
    :return: Polygon of area representing the set of points
    :return: Polygon of area representing the set of points
    """
    out_poly = Polygon()
    h_step = 0.51/scale
    for pos in coords:
        # sum up each polygon
        out_poly.addContour([
            (pos[0] - h_step, pos[1] - h_step),
            (pos[0] + h_step, pos[1] - h_step),
            (pos[0] + h_step, pos[1] + h_step),
            (pos[0] - h_step, pos[1] + h_step)
        ])

    out_poly.simplify()
    return out_poly
Example #48
0
def main(filein, fileout, width, height, gap):
    d = dxfgrabber.read(filein)

    def flipxy(p):
        return (p[1], p[0])

    layers = {}
    for r in d.entities:
        if not r.layer in layers:
            layers[r.layer] = []
        layers[r.layer].append(map(flipxy, r.points))

    polys_to_cut = []
    for (_, ps) in layers.iteritems():
        polys_to_cut += map(lambda p: geo.extend_poly(gap, p, False), ps)

    h = height / 2.0
    w = width / 2.0

    gndplane = Polygon([(h, w), (-h, w), (-h, -w), (h, -w)])

    for p in polys_to_cut:
        gndplane = gndplane - Polygon(p)

    # Polygon.triStrip() returns a list of tristrips which need to be
    # turned into quads, and the list needs to be flattened.
    layers["GROUND"] = [
            quad for quads in map(
                geo.tristrip_to_quads,
                gndplane.triStrip())
            for quad in quads]

    drawing = DXFEngine.drawing(fileout)
    for (l, qs) in layers.iteritems():
        for q in qs:
            drawing.add(DXFEngine.face3d(map(flipxy, q), layer=l))
    drawing.save()
    def __init__(self,minDist=100,maxDist=1000,minPoints=3,maxPoints=1000,startY=33.230073,startX=-97.143826):
        self.minDist = minDist
        self.maxDist = maxDist
        self.minPoints = minPoints
        self.maxPoints = maxPoints
        self.randPoints = random.randrange(self.minPoints,self.maxPoints)
        self.startX = startX
        self.startY = startY

        self.currIteration = 0.0
        self.maxIteration = self.maxPoints

        self.polygon = Polygon()
        self.points = []

        self.generatePolygon()
Example #50
0
    def __init__(self, vertices, color=(255, 255, 255), velocity=(0, 0), angular_velocity=0, colors=None):
        if isinstance(vertices, Polygon):
            self.poly = vertices
        else:
            self.poly = Polygon(vertices)

        self.colors = colors
        self._color = "primary"
        if colors:
            self.color = color

        else:
            self.colors = {"primary": color}

        self.velocity = np.asarray(velocity)
        self.angular_velocity = angular_velocity

        # Construct vertex_list.
        self._vertex_list = self._get_vertex_list()
        self.enabled = True
Example #51
0
class MPolygon:
	"""
	this class will eventually stop the mess with Polygon classes
	
	"""
	def __init__(self, id, points, mode='tuple', data=None):
		from Polygon import Polygon as Poly
		self.poly = Poly()
		
	def __str__(self):
		return '<M;Polygon ('+str(len(self.points))+' points)>'


	def svgPathString(self, useInt=True):
		"""
		returns the path string representation of this polygon
		"""
		ps = ''
		pts = self.points[:]
		if self.closed:
			pts.append(pts[0])
		for pt in pts:
			if pt.deleted: continue #ignore deleted points
			if ps == '': ps = 'M'
			else: ps += 'L'
			if useInt:
				ps += '%d,%d' % (round(pt.x), round(pt.y))
			else:
				ps += '%.3f,%.3f' % (pt.x, pt.y)
		if self.closed: 
			ps += 'Z' # close path
		return ps
		

	def area(self):
		return self.poly.area()
Example #52
0
File: Test.py Project: ducino/dig
def on_key_press(symbol, modifiers):
    global actor
    
    if symbol == key.LEFT:
        actor.controls.pressedLeft = True
    if symbol == key.RIGHT:
        actor.controls.pressedRight = True
    if symbol == key.UP:
        actor.controls.pressedUp = True
    if symbol == key.DOWN:
        actor.controls.pressedDown = True
    if symbol == key.SPACE:
        actor.controls.pressedJump = True
        
    global polygon2
    global debug

    if symbol == key.A:
        polygon2 = Polygon.createBoundingBoxPolygon(Vector(-20, -20), Vector(40, 0))
        polygon2.midpointDisplacement(8)
        polygon2.midpointDisplacement(6)
        polygon2.triangulate()
    if symbol == key.Z:
        debug = (debug + 1)%4
Example #53
0
def get_cube_polygons():
    # a cube consist of six faces
    # left
    polygons = []
    rec = Polygon(get_rectangle_points())
    t = get_shift_matrix(-1, 0, 0).dot(get_rot_y_matrix(math.pi/2))
    polygons.append(rec.transform(t))
    # right
    t = get_shift_matrix(1, 0, 0).dot(get_rot_y_matrix(math.pi/2))
    polygons.append(rec.transform(t))
    # bottom
    t = get_shift_matrix(0, -1, 0).dot(get_rot_x_matrix(math.pi/2))
    polygons.append(rec.transform(t))
    # top
    t = get_shift_matrix(0, 1, 0).dot(get_rot_x_matrix(math.pi/2))
    polygons.append(rec.transform(t))
    # front
    t = get_shift_matrix(0, 0, -1)
    polygons.append(rec.transform(t))
    # back
    t = get_shift_matrix(0, 0, 1)
    polygons.append(rec.transform(t))
    return polygons
Example #54
0
def main():

    size = True
    n = 0
    #pointt = [Point(0, 0), Point(1, 3), Point(1, 2), Point(2, 3), Point(4, 1), Point(5, 1), Point(5, 0)]
    pointt = [Point(0, -4), Point(0, 2), Point(-3, -1), Point(3, -1), Point(-1, 0), Point(1, -2), Point(1, 0) , Point(-1, -2)]
    point = [Point(0, 5), Point(5, 0), Point(0, -5), Point(-5, 0)]
    points = []
    counter = 0
    control_point = 0
    with open('data.txt') as f:
        for line in f:
            int_list = [float(i) for i in line.split()]
            counter += 1
            if counter == 1:
                n = int_list[0]
                control_point = Point(int_list[1],int_list[2])
            else:
                if counter <= n+1:
                    points.append(Point(int_list[0],int_list[1]))
                #print int_list


    # for i in points:
    #     print(i._x   )
    #     print(  i._y)

    control_point = Point(2,2)

    poly = Polygon(pointt, False)
    print(poly.get_area())

    print(poly.is_point_belongs(control_point))
    print(poly.is_point_belongs_another(control_point))


    poly.write_to_file()

    return
 def __mutate5__( code ):
     idxToChange = randint( 0 , len( code._polygons )-1 )
     polygon = code._polygons[ idxToChange ]
     newVertex = Polygon.rand_xy( IMG_WIDTH , IMG_HEIGHT )
     polygon._vertices.append( newVertex )