def ClosestIntersectionPointOnBorder( self, p1, p2, border ): line = Line(p1, p2) intersectionPointList = [] # check intersecting outer borders on line to closest pair point if border == 0: for l in self.outerBorder.lineList: p = line.GetIntersectionPoint(l) if p: # print 'Found OB intersection!' intersectionPointList.append(p) elif border > 0: # check intersecting inner borders on line to closest pair point shape = self.innerBorders[border - 1] for l in shape.lineList: p = line.GetIntersectionPoint(l) if p: #print 'Found IB intersection!' #print p.intersectingLine.p1.borderId intersectionPointList.append(p) # if any intersections found return the closest if len(intersectionPointList) > 0: # print 'Returning Closest Intersection point!' return self.ClosestPoint(intersectionPointList, p2) else: return None
def draw(self, save=False, nr=0): plt.clf() plt.axis('off') plt.axis('equal') nodes = self.get_node_positions() for i in range(len(nodes)): node = nodes[i] if not node: continue color = "black" if i <= const.car_sensor_count: color = "purple" if i == self.n - 1: color = "green" if i == self.n - 2: color = "pink" plt.scatter(node.x, node.y, s=100, color=color, zorder=100) for i in range(self.n): for j in range(self.n): if self.edges[i][j]: line = Line(nodes[i], nodes[j]) X, Y = line.plot_data() color = "red" if self.weights[i][j] < 0: color = "blue" plt.plot(X, Y, zorder=abs(self.weights[i][j]), color=color, linewidth=self.weights[i][j]) if save: plt.savefig(const.dag_evolution_path_root + 'brain' + str(nr)) else: plt.show()
def AltClosestIntersectionPoint( self, p1, p2 ): border = p1.borderId print "AltClosestIntersectionPoint" #print ("BorderId:", border) line = Line( p2, p1 ) intersectionPointList = [] # check intersecting outer borders on line to closest pair point for l in self.outerBorder.lineList: p = line.GetIntersectionPoint( l ) if p and p.intersectingLine.p1.borderId != border: # print 'Found OB intersection!' intersectionPointList.append( p ) # check intersecting inner borders on line to closest pair point for shape in self.innerBorders: for l in shape.lineList: p = line.GetIntersectionPoint( l ) if p and p.intersectingLine.p1.borderId != border: #print 'Found IB intersection!' #print ("intersection has border Id:", p.intersectingLine.p1.borderId ) intersectionPointList.append( p ) # if any intersections found return the closest if len(intersectionPointList) > 0: # print 'Returning Closest Intersection point!' return self.ClosestPoint( intersectionPointList, p1 ) else: return None
def clip_line_plane(line, plane, small_z=0): p0 = line[0] p1 = line[1] n = plane.normal th = plane.threshold + small_z p0n = vec.dot(p0, n) p1n = vec.dot(p1, n) p0_safe = p0n >= th p1_safe = p1n >= th #if both vertices are behind, draw neither if (not p0_safe) and (not p1_safe): return None #both vertices in front if p0_safe and p1_safe: return line #if one of the vertices is behind the camera t_intersect = (p0n - th) / (p0n - p1n) intersect = vec.linterp(p0, p1, t_intersect) if (not p0_safe) and p1_safe: return Line(intersect, p1) else: return Line(p0, intersect)
def onClash(self, object, position): if self.isHard(): Clash(self.game, pos=position) object.hitSpeedup(self.getLength()/config.MAX_BAT_LENGTH) self.__playSound(position) Line.onClash(self, object ,position) return False
def rectangle(l): p = Point(np.random.uniform(low=-l/2, high=l/2), np.random.uniform(low=0, high=l/2)) w = np.random.uniform(low=0, high=l/3) h = np.random.uniform(low=0, high=l/6) a = np.random.uniform(low=-np.pi/4, high=np.pi/4) p1 = p.translation(w, h).rotation(a, p) p2 = p.translation(w, -h).rotation(a, p) p3 = p.translation(-w, -h).rotation(a, p) p4 = p.translation(-w, h).rotation(a, p) return Polyline([Line(p1, p2), Line(p2, p3), Line(p3, p4), Line(p4, p1)])
def clip_line(line, boundaries): p0 = line[0] p1 = line[1] a = 0. b = 1. p0_all_safe, p1_all_safe = False, False for boundary in boundaries: n = boundary.normal th = boundary.threshold p0n = vec.dot(p0, n) p1n = vec.dot(p1, n) p0_safe = p0n >= th p1_safe = p1n >= th if p0_safe and p1_safe: a = 0 b = 1 p0_all_safe = True p1_all_safe = True break #print('p0,p1 safe',p0_safe,p1_safe) if p0_safe and (not p1_safe): t_intersect = (p0n - th) / (p0n - p1n) a = max(a, t_intersect) #print('move a to',a) if (not p0_safe) and p1_safe: t_intersect = (p0n - th) / (p0n - p1n) b = min(t_intersect, b) #print('move b to',b) p0_all_safe = (p0_all_safe or p0_safe) p1_all_safe = (p1_all_safe or p1_safe) #print('all_safe',p0_all_safe,p1_all_safe) #both endpoints visible if p0_all_safe and p1_all_safe: #return two lines if we've intersected the shape if a > 0 and b < 1: return [ Line(p0, vec.linterp(p0, p1, a)), Line(vec.linterp(p0, p1, b), p1) ] else: #return entire line if we haven't intersected the shape return [line] if p0_all_safe and (not p1_all_safe): return [Line(p0, vec.linterp(p0, p1, a))] if (not p0_all_safe) and p1_all_safe: return [Line(vec.linterp(p0, p1, b), p1)] #if neither point is visible, don't draw the line return []
def scale(self, factor_w, factor_h): for point in self.points: point.x *= factor_w point.y *= factor_h self.lines = [] for i in range(0, 3): self.lines.append(Line.Line(self.points[i], self.points[i + 1])) self.lines.append(Line.Line(self.points[-1], self.points[0]))
def get_polyline(self, fat=1): dxh = self.height * fat * np.cos(self.alpha) dyh = self.height * fat * np.sin(self.alpha) dxw = self.width * fat * np.cos(self.alpha - np.pi / 2) dyw = self.width * fat * np.sin(self.alpha - np.pi / 2) p1 = self.pos.translation(dxh, dyh).translation(dxw, dyw) p2 = self.pos.translation(dxh, dyh).translation(-dxw, -dyw) p3 = self.pos.translation(-dxh, -dyh).translation(dxw, dyw) p4 = self.pos.translation(-dxh, -dyh).translation(-dxw, -dyw) return Polyline( [Line(p1, p2), Line(p2, p4), Line(p3, p4), Line(p3, p1)])
def dobounce(self, line): moveline = Line(self, Point2D(self.nextx,self.nexty)) intersection = moveline.collide(line) # lines do not HAVE to intersect! if not intersection: print "lines are parallel" return False normale = line.getNormal() if (abs(winkelabstand(normale+math.pi,self.direction)) > abs(winkelabstand(normale,self.direction))): normale += math.pi einfall = winkelabstand(normale, self.direction+math.pi) ausfall = normale + einfall self.direction = ausfall;
def trybounce(self, line): self.updateNext() moveline = Line(self, Point2D(self.nextx,self.nexty)) intersection = moveline.clash(line) if (intersection): return line.onClash(self, intersection) # print "doing bounce of %s <> %s: %s" % (moveline,line,intersection) # if(line.isHard()): # print "hardbounce" # self.dobounce(line) # return True # else: # return False return False
def testCircleDoesIntersectLineInstanceMethod(self): c = Circle() l = Line(c.a, c.a_neg) with self.assertRaises(NotImplementedError): c.doesIntersect(l)
def serpent(segments, sharpness): lines = [Line(Point(0., 0.), Point(0., 10.))] a = np.pi / 2 xprv = 0. yprv = 10. sgn = -1 for s in range(segments): for i in range(sharpness): a += (np.pi / sharpness) * sgn x = xprv + 10. * np.cos(a) y = yprv + 10. * np.sin(a) lines.append(Line(Point(xprv, yprv), Point(x, y))) xprv = x yprv = y sgn *= -1 return Polyline(lines)
def validate_alignment(self): ''' Ensure the alignment geometry is continuous. Any discontinuities (gaps between end / start coordinates) must be filled by a completely defined line ''' _prev_coord = self.geometry['meta']['Start'] _geo_list = [] for _geo in self.geometry['geometry']: if not _geo: continue _coord = _geo['Start'] if not Support.within_tolerance(_coord.Length, _prev_coord.Length): #build the line using the provided parameters and add it _geo_list.append( Line.get_parameters({ 'Start': App.Vector(_prev_coord), 'End': App.Vector(_coord), 'BearingIn': _geo['BearingIn'], 'BearingOut': _geo['BearingOut'], })) _geo_list.append(_geo) _prev_coord = _geo['End'] self.geometry['geometry'] = _geo_list
def circular(n, circ_dir): lines = [Line(Point(0., 0.), Point(0., 10.))] a = np.pi / 2 xprv = 0. yprv = 10.0 sgn = -1 ### turn right if circ_dir == 'left': sgn = 1 for i in range(n): a += 0.2 * sgn l = 2 * np.sqrt(i + 10) x = xprv + l * np.cos(a) y = yprv + l * np.sin(a) lines.append(Line(Point(xprv, yprv), Point(x, y))) xprv = x yprv = y return Polyline(lines)
def test_case_2(self): groove_area = [ Vector(0, 5), Vector(100, 5), Vector(0, -5), Vector(100, -5) ] lines = GrooveEvaluator.calculate_groove_passes(groove_area, True, tool_thickness=8, tool_interlock=1) expected_lines = [ Line(Vector(0, -1), Vector(100, -1)), Line(Vector(0, 1), Vector(100, 1)) ] self.assertListEqual(expected_lines, lines)
def draw_normals(camera, shape, color): lines = [ Line(face.center, face.center + face.normal) for face in shape.faces ] lines = Clipping.camera_clip_lines(lines, camera) if len(lines) < 1: return draw_lines(camera, lines, color)
def create_layer_lines(self, points1, points2, weights): lines = [] for i in range(weights.shape[0]): for j in range(weights.shape[1]): color = "red" if weights[i][j] < 0: color = "blue" lines.append((Line(points1[i], points2[j]), color, weights[i][j])) return lines
def test_getLength(self): a = Line(Point2D(1,2),Point2D(4,2)) self.assertEqual(a.getLength(), 3.0) a = Line((1,2),(1,5)) self.assertEqual(a.getLength(), 3.0) a = Line((0,0),(3,4)) self.assertEqual(a.getLength(), 5.0) a = Line((0,0),(0,0)) self.assertEqual(a.getLength(), 0.0)
def horseshoe(n, circ_dir): lines = [Line(Point(0., 0.), Point(1., 10. * n))] a = np.pi / 2 xprv = 1. yprv = 10. * n sgn = -1 if circ_dir == 'left': sgn = 1 for i in range(9): a += np.pi / 10 * sgn x = xprv + 10 * np.cos(a) y = yprv + 10 * np.sin(a) lines.append(Line(Point(xprv, yprv), Point(x, y))) xprv = x yprv = y x = xprv + 10 * n * np.cos(a) y = yprv + 10 * n * np.sin(a) lines.append(Line(Point(xprv, yprv), Point(x, y))) return Polyline(lines)
def random_path(n, sigma, l): lines = [Line(Point(0., 0.), Point(0.5, l))] a = np.pi / 2 xprv = 0.5 yprv = l for i in range(n): turn = np.random.normal(0, sigma) if turn < 0: turn = max(turn, -sigma) else: turn = min(turn, sigma) a += turn l = np.random.random() * l + 2 x = xprv + l * np.cos(a) y = yprv + l * np.sin(a) lines.append(Line(Point(xprv, yprv), Point(x, y))) xprv = x yprv = y return Polyline(lines)
def create_arm(angles, lengths): alpha = np.pi/2 A = Point(0, 0) lines = [] for i in range(len(angles)): B = A.translation(lengths[i], 0) alpha += angles[i] B = B.rotation(alpha, A) lines.append(Line(A, B)) A = B return Polyline(lines)
def __init__(self, n, width=const.learn_track_width, curvature=0.5, path_type='random', circ_dir='right', segments=5, sharpness=10): self.left, self.right = generate_path(n, width, curvature, path_type=path_type, circ_dir=circ_dir, segments=segments, sharpness=sharpness) self.finish = Polyline( [Line(self.left.lines[-1].b, self.right.lines[-1].b)]) self.start = Polyline( [Line(self.left.lines[0].a, self.right.lines[0].a)])
def clip_line_sphere(line, r): v0 = line[0] v1 = line[1] v0_in_sphere = vec.dot(v0, v0) < r * r v1_in_sphere = vec.dot(v1, v1) < r * r #print('v0_in_sphere',v0_in_sphere) #print('v1_in_sphere',v1_in_sphere) if v0_in_sphere and v1_in_sphere: return line intersect = sphere_line_intersect(line, r) if intersect is None: return None if (not v0_in_sphere) and (not v1_in_sphere): return intersect if (not v0_in_sphere) and v1_in_sphere: return Line(intersect[0], v1) else: return Line(v0, intersect[1])
def test_case_6(self): groove_area = [ Vector(-1, 479.1), Vector(451, 479.1), Vector(-1, 469.1), Vector(451, 469.1) ] lines = GrooveEvaluator.calculate_groove_passes(groove_area, True, tool_thickness=3.2, tool_interlock=1) expected_lines = [ Line(Vector(-1, 470.7), Vector(451, 470.7)), Line(Vector(-1, 477.5), Vector(451, 477.5)), Line(Vector(-1, 472.9), Vector(451, 472.9)), Line(Vector(-1, 475.3), Vector(451, 475.3)), Line(Vector(-1, 475.1), Vector(451, 475.1)), ] self.assertListEqual(expected_lines, lines)
def test_case_7(self): groove_area = [ Vector(0, 10), Vector(20, 10), Vector(0, 0), Vector(20, 0) ] lines = GrooveEvaluator.calculate_groove_passes(groove_area, True, tool_thickness=3, tool_interlock=1) expected_lines = [ Line(Vector(0, 1.5), Vector(20, 1.5)), Line(Vector(0, 8.5), Vector(20, 8.5)), Line(Vector(0, 3.5), Vector(20, 3.5)), Line(Vector(0, 6.5), Vector(20, 6.5)), Line(Vector(0, 5.5), Vector(20, 5.5)), ] self.assertListEqual(expected_lines, lines)
def traverse(self, lengths, angles): lines = [] end_points = [] self.angle = self.parent.angle + angles[0] self.p = self.parent.p.translation(lengths[0], 0).rotation(self.angle, self.parent.p) lines.append(Line(self.parent.p, self.p)) for son in self.sons: lengths, angles, l, e= son.traverse(lengths[1:], angles[1:]) lines += l end_points += e if len(self.sons) == 0: end_points.append(self.p) return lengths, angles, lines, end_points
def get_sensors(self, track): sensors = [] angles = [np.pi / 2, np.pi / 4, 0., -np.pi / 4, -np.pi / 2] dx0 = self.height * np.cos(self.alpha) dy0 = self.height * np.sin(self.alpha) p0 = self.pos.translation(dx0, dy0) for angle in angles: dx = self.sensor_length * np.cos(self.alpha) dy = self.sensor_length * np.sin(self.alpha) p1 = p0.translation(dx, dy).rotation(angle, p0) sensors.append(Line(p0, p1)) for sensor in sensors: sensor.adjust_to_track(track) return sensors
def moveBounce(self, end, new): """ O = old point -> moved batend N = new point -> new position F = fixpoint -> other bat-end """ F = self.ends[0] O = self.ends[1] if (end != O): (F,O) = (O,F) N = new T = Triangle(F, O, N) if isinstance(self.game.curState, PlayingState): ball = self.game.curState.ball if T.contains(ball): self.__playSound(N) # if Line(F,N).getAngle()-Line(F,O).getAngle()<0.05: # return # print "triangle: %s, ball=%s" % (T,ball) moveline = Line(O,N) newdir = moveline.getAngle() + 0.01 ball.direction = newdir ball.updateNext() newbat = Line(F, N) movevect = Point2D(ball.nextx, ball.nexty) - ball futurepos = ball + 100 * movevect ballmove = Line(ball, futurepos) newpos = newbat.collide(ballmove) # print "%s and %s collide at %s" % (newbat,moveline,newpos) if (newpos): #XXX ball.goto(newpos.x,newpos.y) else: print "warning: no newpos!" Clash(self.game, pos=ball) ball.hitSpeedup(self.getLength()/(config.MAX_BAT_LENGTH*2)) ball.update()
def ClosestIntersectionPointToDst( self, p1, p2 ): line = Line(p1, p2) intersectionPointList = [] # check intersecting outer borders on line to closest pair point for l in self.outerBorder.lineList: p = line.GetIntersectionPoint(l) if p: # print 'Found OB intersection!' intersectionPointList.append(p) # check intersecting inner borders on line to closest pair point for shape in self.innerBorders: for l in shape.lineList: p = line.GetIntersectionPoint(l) if p: # print 'Found IB intersection!' # print p.borderId intersectionPointList.append(p) # if any intersections found return the closest if len(intersectionPointList) > 0: # print 'Returning Closest Intersection point!' return self.ClosestPoint(intersectionPointList, p2) else: return None
def test_getAngle(self): a = Line((0,0),(3,4)) self.assert_(floatEqual(a.getAngle(), 0.9272952180016123)) a = Line((5,0),(3,3)) self.assert_(floatEqual(a.getAngle(), 2.158798930342464)) a = Line((4,3),(0,0)) self.assert_(floatEqual(a.getAngle(), 3.7850937623830774)) a = Line((3,3),(5,5)) self.assert_(floatEqual(a.getAngle(), 0.78539816339744817)) try: Line((1,2),(1,2)).getAngle() except: self.fail("zero length Line.getAngle() threw an exception")
def __init__(self, points): self.points = [] self.lines = [] x = y = 0 if len(points ) < 4: # add original point in the end, so the minimum point =4 print "This polygon has less than 3 points" if points[0] != points[-1]: print "This polygon end point != starting point" for count, point in enumerate(points): self.points.append(point) if len(self.points) > 1: self.lines.append( Line.Line(self.points[count - 1], self.points[count]))
def input_polyfile(self): filename = str( input("Please insert polygon csv filename(i.e., file.csv): ")) with open(filename, "r") as file: next(file) polygon_points = [] # store point objects of the polygon points x_polygon = [] # store x coordinates of polygon y_polygon = [] # store y coordinates of polygon for line in file: data = line.strip().split(",") # use data to make point objects polygon_points.append( Point(float(data[0]), float(data[1]), float(data[2]))) x_polygon.append(float(data[1])) y_polygon.append(float(data[2])) polygon_lines = [] # store the line objects of the polygon points prev = polygon_points[0] for i in polygon_points[1:]: polygon_lines.append(Line(prev, i)) prev = i return polygon_points, x_polygon, y_polygon, polygon_lines
def set_geometry(self, geometry): ''' Assign geometry to the alignment object ''' self.geometry = geometry self.assign_meta_data() self.assign_station_data() for _i, _geo in enumerate(self.geometry['geometry']): if _geo['Type'] == 'Curve': _geo = Arc.get_parameters(_geo) elif _geo['Type'] == 'Line': _geo = Line.get_parameters(_geo) else: self.errors.append('Undefined geometry: ' + _geo) continue self.geometry['geometry'][_i] = _geo self.validate_datum() self.validate_stationing() if not self.validate_bearings(): return False self.validate_coordinates() self.validate_alignment() #call once more to catch any added geometry from validate_alignment() self.validate_stationing() return True
def test_case_5(self): groove_area = [ Vector(-1, 479.1), Vector(1001, 479.1), Vector(-1, 469.1), Vector(1001, 469.1) ] lines = GrooveEvaluator.calculate_groove_passes(groove_area, True, tool_thickness=2.2, tool_interlock=1) expected_lines = [ Line(Vector(-1, 470.2), Vector(1001, 470.2)), Line(Vector(-1, 478.0), Vector(1001, 478.0)), Line(Vector(-1, 471.4), Vector(1001, 471.4)), Line(Vector(-1, 476.8), Vector(1001, 476.8)), Line(Vector(-1, 472.6), Vector(1001, 472.6)), Line(Vector(-1, 475.6), Vector(1001, 475.6)), Line(Vector(-1, 473.8), Vector(1001, 473.8)), Line(Vector(-1, 474.4), Vector(1001, 474.4)) ] self.assertListEqual(expected_lines, lines)
def LineSweep(self): self.sweepLines = [] self.collisionGroups = [] distX = self.boundingBox[0].DistToPoint(self.boundingBox[1].x, self.boundingBox[1].y) distY = self.boundingBox[0].DistToPoint(self.boundingBox[3].x, self.boundingBox[3].y) print('Distance X:', distX) print('Distance Y:', distY) if self.sweepAngle == 0 or self.sweepAngle == 180: # traverse down on y-axis y = 0 count = 0 trigger = self.sweepOffset while True: if y >= distY: break # "Fire line ray" if y >= trigger: p1 = Point(self.boundingBox[0].x, self.boundingBox[0].y + y) p2 = Point(self.boundingBox[0].x + distX, self.boundingBox[0].y + y) l = Line(p1, p2) collisionsOnSameLine = [] # check line intersections and collect intersect points from lawn boundarys for line in self.outerBorder.lineList: point = l.GetIntersectionPoint(line) if point: collisionsOnSameLine.append(point) # check collision with obstacles if len(self.innerBorders) > 0: for shape in self.innerBorders: # check line intersections and collect intersect points from lawn boundarys for line in shape.lineList: point = l.GetIntersectionPoint(line) if point: collisionsOnSameLine.append(point) #prevPoint = point self.SortPoints(collisionsOnSameLine) self.VertexPointAdjust(collisionsOnSameLine) # if len(collisionsOnSameLine) % 2 != 0: print("Error! odd number of collisions on line!") print("num collisions on this line", len(collisionsOnSameLine)) for point in collisionsOnSameLine: print point.x if len(collisionsOnSameLine) > 0: self.collisionGroups.append(collisionsOnSameLine) trigger += self.sweepOffset count += 1 self.sweepLines.append(l) y += 1 count = 0 for points in self.collisionGroups: for point in points: count += 1 print("Number of collision points: ", count) return
def __init__(self, p1, p2): Line.__init__(self, p1, p2)
def onClash(self, object, position): Line.onClash(self, object, position) if isinstance(object, Ball): self.__playSound(position) return True
def __init__(self, p1, p2, player): Line.__init__(self, p1, p2) self.__player = player