static void Main() { //Create some path Path path = new Path(); path.Add(Point3D.Origin); path.Add(new Point3D(0, 0, 5)); path.Add(new Point3D(0, 0, 10)); path.Add(new Point3D(5, 5, 10)); //Save it to a file string file = "../../path.txt"; PathStorage.Save(path, file); //Read it from the file Path pathFromFile = PathStorage.Load(file); //Check if the initial path and the one that we read from file are same bool areTheSame = true; for (int i = 0; i < path.Length; i++) { if (path[i].X != pathFromFile[i].X || path[i].Y != pathFromFile[i].Y || path[i].Z != pathFromFile[i].Z) { areTheSame = false; break; } } Console.WriteLine(areTheSame); }
static void Main(string[] args) { var point = new Point3D(); point.X = 0.5; point.Y = -3; point.Z = 1.35; Console.WriteLine(point); Console.WriteLine(DistanceBetween2Points.Distance(point, Point3D.Start)); Path test = new Path(); Point3D point1 = new Point3D(1, 2, 3); Point3D point2 = new Point3D(-1, 6, 7); Point3D point3 = new Point3D(4, 2, 3); Point3D point4 = new Point3D(-3, -4, 3); Point3D point5 = new Point3D(1.20, 2.35, 3); test.Add(point1); test.Add(point2); test.Add(point3); test.Add(point4); test.Add(point5); PathStorage.SavePath(test, "sample"); Path path = PathStorage.LoadPath(@"pointsample.txt"); for (int i = 0; i < path.Points.Count; i++) { Console.WriteLine("{0}: {1}", i + 1, path.Points[i].ToString()); } }
static void Main(string[] args) { Point3d pointOne = new Point3d(); pointOne.PointX = 0.5; pointOne.PointY = 0.5; pointOne.PointZ = 0.5; Console.WriteLine(pointOne); Console.WriteLine(Point3d.ZeroPosition); Point3d pointTwo = new Point3d(1.5, 1.5, 1.5); Console.WriteLine(pointTwo); Console.WriteLine("Distance between"); Console.WriteLine(Distance.DistanceBetween(pointOne, pointTwo)); Path path = new Path(); path.Add(pointOne); path.Add(pointTwo); PathStorage.SavePath(path, @"../../Points3d.txt"); path.Clear(); Console.WriteLine(); Console.WriteLine("Path is saved and then cleared"); path = PathStorage.LoadPath(@"../../Points3d.txt"); Console.WriteLine(); Console.WriteLine("After reloading again from file"); Console.WriteLine(); foreach (var item in path.Paths) { Console.WriteLine(item); } }
static void Main() { Point3D p = new Point3D(); Point3D q = new Point3D(4, 4, 4); Console.WriteLine(CalcDistance.Distance(p, q)); Path path = new Path(); path.Add(p); path.Add(q); path.Add(new Point3D(9, 9, 9)); Console.WriteLine(path.ToString()); PathStorage.Save(path); Console.WriteLine(PathStorage.Load().ToString()); }
static void Main() { Point3D a = new Point3D(1, 2, 3); Console.WriteLine("Point({0})", a); // point A Point3D b = Point3D.Center; Console.WriteLine("Point({0}, {1}, {2})", b.X, b.Y, b.Z); // point O Console.WriteLine("Distance: {0}", Distance.Calculate(a, b)); // Calculate distance // Path of points Path path = new Path(new Point3D(1, 1, 1), new Point3D(2, 2, 2)); path.Add(new Point3D(3, 3, 3)); path.Remove(new Point3D(1, 1, 1)); Console.WriteLine("\nPoints in path (total: {0})\n{1}", path.Count, path); path.Clear(); // Loads new points from the file path = PathStorage.Load("../../input.txt"); Console.WriteLine("\nPoints in path (total: {0})\n{1}", path.Count, path); // Saves the points in output file PathStorage.Save(path, "../../output.txt"); }
static void Main() { Console.WriteLine("Testing 3D Points, Path and Path Storage....\r\n"); Console.WriteLine("Enter a path as a sequence of 3D points (x y z, separated with spaces, one per line)\r\nFinish with 0,0,0 or wrong input"); Path p1 = new Path(); try { while (true) { Console.Write("Point {0}: ", p1.Count + 1); string[] coords = Console.ReadLine().Split(' '); // reads each point (X,Y,Z, separated by spaces) int x = int.Parse(coords[0]); int y = int.Parse(coords[1]); int z = int.Parse(coords[2]); if (x == 0 && y == 0 && z == 0) break; // finishes input on {0,0,0} p1.Add(x, y, z); // and loads it into the path // calculates the distance between last two entered points if (p1.Count > 1) Console.WriteLine("Distance:" + Distance3D.Calc(p1[p1.Count - 1], p1[p1.Count - 2])); else Console.WriteLine("Distance:" + Distance3D.Calc(p1[p1.Count - 1], Point3D.O)); } } catch { } Console.WriteLine("The result is " + p1); Console.WriteLine("Saves to text file and reads back to another variable"); PathStorage.Write(p1, "..\\..\\testpath.txt"); Path p2 = PathStorage.Read("..\\..\\testpath.txt"); Console.WriteLine(p2); Console.WriteLine("press Enter to finish"); Console.ReadLine(); }
public static List<Path> LoadPath() { List<Path> allPaths=new List<Path>(); using (StreamReader reader = new StreamReader("storage.txt")) { string line=reader.ReadLine(); while(line!=null) { Path onePath = new Path(); string[] onePointCoords=line.Split(';'); foreach (var point in onePointCoords) { string[] coords=point.Split(','); Point3D aPoint=new Point3D(); aPoint.X=double.Parse(coords[0]); aPoint.Y=double.Parse(coords[1]); aPoint.Z=double.Parse(coords[2]); onePath.Add(aPoint); } allPaths.Add(onePath); line=reader.ReadLine(); } } return allPaths; }
static void Main() { Console.WriteLine("# Testing distance"); Console.WriteLine("Distance: {0}", Distance.Calculate(new Point3D(1, 1, 1), Point3D.Zero)); Console.WriteLine("# Testing path"); Path path = new Path( Point3D.Zero, new Point3D(1, 1, 1), new Point3D(1, 2, 1), new Point3D(1, 3, 1) ); Console.WriteLine(path); Console.WriteLine("# Testing add/remove"); Console.WriteLine(path.Add(new Point3D(1, 2, 4)).Remove(new Point3D(1, 1, 1))); Console.WriteLine("# Testing path storage"); PathStorage.Write(path, "../../input.txt"); Console.WriteLine(PathStorage.Load("../../input.txt")); }
static void Main(string[] args) { Console.WriteLine(Point3D.O); Path checkPath = new Path("[0,0,0][1, 3, -4]"); checkPath.Add(Point3D.O); Path probs = new Path("[4,3,5][3,7,8][13,5,2]"); var listOfPaths = new List<Path>(); listOfPaths.Add(probs); listOfPaths.Add(probs); listOfPaths.Add(probs); Console.WriteLine(probs); PathStorage.SavePaths(listOfPaths, "probs"); var secondListOfPaths = new List<Path>(); secondListOfPaths = PathStorage.LoadPaths("probs"); foreach (var path in secondListOfPaths) { Console.WriteLine(path); } }
public static Path LoadPath(string fileFullName) { if (String.IsNullOrWhiteSpace(fileFullName)) { throw new ArgumentException("File name cannot be null or empty."); } if (!File.Exists(fileFullName)) { throw new ArgumentException("The specified file doesn't exist in the local file system."); } Path points = new Path(); using (StreamReader fileReader = new StreamReader(fileFullName)) { string line; while ((line = fileReader.ReadLine()) != null) { string[] coordinates = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); double x, y, z; if (coordinates.Length == 3 && Double.TryParse(coordinates[0], out x) && Double.TryParse(coordinates[1], out y) && Double.TryParse(coordinates[2], out z)) { Point3D point = new Point3D(x, y, z); points.Add(point); } } } return points; }
/// <summary> /// Envia o código de verificação para o número destino /// </summary> /// <param name="Data">Estrutura enviada para o Post.</param> /// // Ex: // var Data = new { // numero_destino = "48988888888", // nome_produto = "Meu teste", // tamanho = 4, // tts = false // }; /// public string Enviar(dynamic Data) { Path path = new Path(); path.Add(ROTA_VERIFICACAO); _request.SetPath(path); _request.SetBody(Data); return(_client.SendRequest(_request, POST)); }
public void LastOfPathWithOnePointIsThatPoint() { var singlePoint = new Point(1, 2); Path path = new Path(); path.Add(singlePoint); Assert.AreEqual(singlePoint, path.Last); }
public void AddPointToPathIncrementsPathLength() { Path path = new Path(); int lengthBefore = path.Length; path.Add(new Point()); int lengthAfter = path.Length; Assert.AreEqual(lengthAfter, lengthBefore + 1); }
/// <summary> /// Move in a gene's direction, and reflect that in the path /// </summary> public void Move() { Direction direction = Genes[StaticUtils.RandomGeneIndex()].Direction; Coordinate newPosition = new Coordinate(CurrentPosition); newPosition.MoveDirection(direction); Path.Add(newPosition); CurrentPosition = newPosition; }
private ChainTest() { //Ground BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f)); //Chain start / end Path path = new Path(); path.Add(new Vector2(0, 25)); path.Add(new Vector2(40, 25)); //A single chainlink PolygonShape shape = new PolygonShape(PolygonTools.CreateRectangle(0.125f, 0.6f), 20); //Use PathFactory to create all the chainlinks based on the chainlink created before. List <Body> chainLinks = PathManager.EvenlyDistributeShapesAlongPath(World, path, shape, BodyType.Dynamic, 30); foreach (Body chainLink in chainLinks) { foreach (Fixture f in chainLink.FixtureList) { f.Friction = 0.2f; } } //Fix the first chainlink to the world FixedRevoluteJoint fixedJoint = new FixedRevoluteJoint(chainLinks[0], Vector2.Zero, chainLinks[0].Position); World.AddJoint(fixedJoint); //Attach all the chainlinks together with a revolute joint List <RevoluteJoint> joints = PathManager.AttachBodiesWithRevoluteJoint(World, chainLinks, new Vector2(0, -0.6f), new Vector2(0, 0.6f), false, false); //The chain is breakable for (int i = 0; i < joints.Count; i++) { RevoluteJoint r = joints[i]; r.Breakpoint = 10000f; } }
//////////////////////////////////////////////// static Path MakeRandomPolygon(Random r, int maxWidth, int maxHeight, int edgeCount, Int64 scale = 1) { Path result = new Path(edgeCount); for (int i = 0; i < edgeCount; i++) { result.Add(new IntPoint(r.Next(maxWidth) * scale, r.Next(maxHeight) * scale)); } return(result); }
public string Enviar(string data) { Path path = new Path(); path.Add(ROTA_TTS); _request.SetPath(path); _request.SetBody(data); return(_client.SendRequest(_request, "POST")); }
/// <summary> /// Envia um Torpedo Composto para um número destino /// </summary> /// DOCS: /// https://totalvoice.github.io/totalvoice-docs/#conferencias /// public string Criar() { Path path = new Path(); path.Add(ROTA_CONFERENCIA); _request.SetPath(path); return(_client.SendRequest(_request, "POST")); }
static void Main() { { Console.WriteLine("# Testing distance"); Console.WriteLine("Distance: {0}", Distance.Calculate(new Point3D(1, 1, 1), Point3D.Zero)); Console.WriteLine(); } { Console.WriteLine("# Testing path"); Point3D point = new Point3D(1, 1, 1); Path path = new Path(); path.Add(point); path.Add(new Point3D(1, 2, 1)); path.Add(new Point3D(1, 3, 1)); path.Add(Point3D.Zero); Console.WriteLine(path); Console.WriteLine(); { Console.WriteLine("# Testing remove"); path.Remove(point); Console.WriteLine(path); Console.WriteLine(); } { Console.WriteLine("# Testing path storage"); PathStorage.Write(path); path = PathStorage.Load(); Console.WriteLine(path); } } }
/// <summary> /// Criar uma Conta /// </summary> /// <param name="Data">Estrutura enviada para o Post.</param> /// // Ex: // var Data = new { // nome = "TotalVoice", // login = "******", // senha = "senhasupersecreta" // ... // }; /// DOCS: /// https://totalvoice.github.io/totalvoice-docs/#gerenciar-contas /// public string Criar(dynamic Data) { Path path = new Path(); path.Add(ROTA_CONTA); _request.SetPath(path); _request.SetBody(Data); return(_client.SendRequest(_request, POST)); }
internal static Path PointFArrayToIntArray(PointF[] points, float scale) { Path result = new Path(); for (int i = 0; i < points.Length; ++i) { result.Add(new IntPoint((int)points[i].X * scale, (int)points[i].Y * scale)); } return(result); }
/// <summary> /// Envia um número pra receber um código de validação /// </summary> /// <param name="Telefone">Numero que sera validado</param> /// public string Enviar(string Telefone) { Path path = new Path(); path.Add(ROTA_BINA); _request.SetPath(path); _request.SetBody(new { telefone = Telefone }); return(_client.SendRequest(_request, POST)); }
/// <summary> /// Atualiza os dados da minha conta /// </summary> /// <param name="Data">Estrutura enviada para o Post.</param> /// public string Atualizar(dynamic Data) { Path path = new Path(); path.Add(ROTA_PERFIL); _request.SetPath(path); _request.SetBody(Data); return(_client.SendRequest(_request, PUT)); }
/* * * Geometry features (Offset) * */ public Polygon OffsetPolygon(float offset) { // Calculate Polygon-Clipper scale. float maximum = Mathf.Max(bounds.width, bounds.height) + offset * 2.0f + offset; float scale = (float)Int32.MaxValue / maximum; // Convert to Clipper. Paths paths = new Paths(); { Path path = new Path(); EnumeratePoints((Vector2 eachPoint) => { path.Add(new IntPoint(eachPoint.x * scale, eachPoint.y * scale)); }); paths.Add(path); } foreach (Polygon eachPolygon in polygons) { Path path = new Path(); eachPolygon.EnumeratePoints((Vector2 eachPoint) => { path.Add(new IntPoint(eachPoint.x * scale, eachPoint.y * scale)); }); paths.Add(path); } // Clipper offset. Paths solutionPaths = new Paths(); ClipperOffset clipperOffset = new ClipperOffset(); clipperOffset.AddPaths(paths, JoinType.jtMiter, EndType.etClosedPolygon); clipperOffset.Execute(ref solutionPaths, (double)offset * scale); // Convert from Cipper. Polygon offsetPolygon = null; for (int index = 0; index < solutionPaths.Count; index++) { Path eachSolutionPath = solutionPaths[index]; Polygon eachSolutionPolygon = PolygonFromClipperPath(eachSolutionPath, scale); if (index == 0) { offsetPolygon = Polygon.PolygonWithPoints(eachSolutionPolygon.points); // Copy } else { offsetPolygon.AddPolygon(eachSolutionPolygon); } } // Back to Polygon. return(offsetPolygon); }
private void RealTime(List <Request> requests) { List <Request> queue = new List <Request>(); int waitingTime = 0; bool repeat; for (int y = 0; ; y++) { if (requests.Count == 0 && queue.Count == 0) { break; } if (requests.Count != 0) { do { repeat = false; if (y == requests.First().EntryTime) { queue.Add(requests.First()); requests.Remove(requests.First()); repeat = true; if (requests.Count == 0) { break; } } } while (repeat); } if (waitingTime == 0 && queue.Count != 0) { int length = Math.Abs(position - queue[0].Position); Request element = queue[0]; for (int j = 1; j < queue.Count; j++) { if (length > Math.Abs(position - queue[j].Position)) { length = Math.Abs(position - queue[j].Position); element = queue[j]; } } Path.Add(element); position = element.Position; PathLength = PathLength + length; queue.Remove(element); waitingTime = length; } if (waitingTime > 0) { waitingTime--; } } }
/// <summary> /// Creates a chain. /// </summary> /// <param name="world">The world.</param> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <param name="linkWidth">The width.</param> /// <param name="linkHeight">The height.</param> /// <param name="numberOfLinks">The number of links.</param> /// <param name="linkDensity">The link density.</param> /// <param name="attachRopeJoint">Creates a rope joint between start and end. This enforces the length of the rope. Said in another way: it makes the rope less bouncy.</param> /// <returns></returns> public static Path CreateChain(World world, Vector2 start, Vector2 end, float linkWidth, float linkHeight, int numberOfLinks, float linkDensity, bool attachRopeJoint) { Debug.Assert(numberOfLinks >= 2); //Chain start / end Path path = new Path(); path.Add(start); path.Add(end); //A single chainlink PolygonShape shape = new PolygonShape(PolygonTools.CreateRectangle(linkWidth, linkHeight), linkDensity); //Use PathManager to create all the chainlinks based on the chainlink created before. List <Body> chainLinks = PathManager.EvenlyDistributeShapesAlongPath(world, path, shape, BodyType.Dynamic, numberOfLinks); //TODO //if (fixStart) //{ // //Fix the first chainlink to the world // JointFactory.CreateFixedRevoluteJoint(world, chainLinks[0], new Vector2(0, -(linkHeight / 2)), // chainLinks[0].Position); //} //if (fixEnd) //{ // //Fix the last chainlink to the world // JointFactory.CreateFixedRevoluteJoint(world, chainLinks[chainLinks.Count - 1], // new Vector2(0, (linkHeight / 2)), // chainLinks[chainLinks.Count - 1].Position); //} //Attach all the chainlinks together with a revolute joint PathManager.AttachBodiesWithRevoluteJoint(world, chainLinks, new Vector2(0, -linkHeight), new Vector2(0, linkHeight), false, false); if (attachRopeJoint) { JointFactory.CreateRopeJoint(world, chainLinks[0], chainLinks[chainLinks.Count - 1], Vector2.Zero, Vector2.Zero); } return(path); }
/// <summary> /// Формирует обрезанный путь, начиная с k-й точки до конца /// </summary> private Path truncatePath(Path path, int k) { Path result = new Path(); for (int i = k; i < path.Count; i++) { result.Add(path[i]); } return(result); }
public static Path ToPath(this IEnumerable <Vector2d> vector2Ds) { Path _Path = new Path(); foreach (Vector2d vector2d in vector2Ds) { IntPoint _IntPoint = vector2d.ToIntPoint(); _Path.Add(_IntPoint); } return(_Path); }
//////////////////////////////////////////////// static Path IntsToPolygon(int[] ints) { int len1 = ints.Length / 2; Path result = new Path(len1); for (int i = 0; i < len1; i++) { result.Add(new IntPoint(ints[i * 2], ints[i * 2 + 1])); } return(result); }
public Path ToClipperPath() { var result = new Path(Points.Count); foreach (var point in Points) { result.Add(new IntPoint(point.X, point.Y)); } return(result); }
/** * 坐标转换,与clipper库交互必须坐标转换 * @param polygon * @return */ public static Path scaleUp2ClipperCoordinates(NestPath polygon) { Path p = new Path(); foreach (Segment s in polygon.getSegments()) { ClipperCoor cc = CommonUtil.toClipperCoor(s.x, s.y); p.Add(new IntPoint(cc.getX(), cc.getY())); } return(p); }
/// <summary> /// Creates the chain. /// </summary> /// <returns>The chain.</returns> /// <param name="world">World.</param> /// <param name="start">Start.</param> /// <param name="end">End.</param> /// <param name="linkWidth">Link width.</param> /// <param name="linkHeight">Link height.</param> /// <param name="numberOfLinks">Number of links.</param> /// <param name="linkDensity">Link density.</param> /// <param name="attachRopeJoint">Creates a rope joint between start and end. This enforces the length of the rope. Said in another way: it makes the rope less bouncy.</param> /// <param name="fixStart">If set to <c>true</c> fix start.</param> /// <param name="fixEnd">If set to <c>true</c> fix end.</param> public static List <Body> CreateChain(World world, Vector2 start, Vector2 end, float linkWidth, float linkHeight, int numberOfLinks, float linkDensity, bool attachRopeJoint, bool fixStart = false, bool fixEnd = false) { Debug.Assert(numberOfLinks >= 2); // Chain start / end var path = new Path(); path.Add(start); path.Add(end); // A single chainlink var shape = new PolygonShape(PolygonTools.CreateRectangle(linkWidth, linkHeight), linkDensity); // Use PathManager to create all the chainlinks based on the chainlink created before. var chainLinks = PathManager.EvenlyDistributeShapesAlongPath(world, path, shape, BodyType.Dynamic, numberOfLinks); if (fixStart) { // Fix the first chainlink to the world var axle = BodyFactory.CreateCircle(world, 0.1f, 1, chainLinks[0].Position); JointFactory.CreateRevoluteJoint(world, chainLinks[0], axle, new Vector2(0, -(linkHeight / 2)), Vector2.Zero); } if (fixEnd) { // Fix the last chainlink to the world var lastIndex = chainLinks.Count - 1; var axle = BodyFactory.CreateCircle(world, 0.1f, 1, chainLinks[lastIndex].Position); JointFactory.CreateRevoluteJoint(world, chainLinks[lastIndex], axle, new Vector2(0, -(linkHeight / 2)), Vector2.Zero); } // Attach all the chainlinks together with a revolute joint PathManager.AttachBodiesWithRevoluteJoint(world, chainLinks, new Vector2(0, -linkHeight), new Vector2(0, linkHeight), false, false); if (attachRopeJoint) { JointFactory.CreateRopeJoint(world, chainLinks[0], chainLinks[chainLinks.Count - 1], Vector2.Zero, Vector2.Zero); } return(chainLinks); }
// A method name follows Pascal Casing convention. public static void Main() { Point p1; p1 = new Point(); Point p2 = new Point(); Point p3 = new Point(3, 7); Point p4; Point p5 = new Point(3, 7); p4 = p3; p1.Show(); p2.Show(); Console.WriteLine(p1 == p2); p1 = p4; p4.Show(); p1.Show(); Console.WriteLine(p1 == p2); Console.WriteLine(p1 == p4); Console.WriteLine(p5 == p4); Console.WriteLine(p1.Distance(p2)); Console.WriteLine(p1.Distance(new Point(4, 6))); Console.WriteLine(p1.Distance(4, 6)); Path pt = new Path(5); pt.Add(2, 3); pt.Add(4, 7); pt.Add(1, 8); Console.WriteLine($"{pt.Length():F2}"); Path pt2 = new Path(5); pt2.Add(2, 3); pt2.Add(4, 7); pt2.Add(1, 8); Console.WriteLine($"{pt2.Length():F2}"); Console.WriteLine(pt.Compare(pt2)); }
public void AddCollisionPolygon(CollisionDefinitionEntry entry) { var path = new Path(); foreach (var point in entry.Vertices) { path.Add(ConvertUnits.ToSimUnits(point)); } path.Closed = true; PathManager.ConvertPathToPolygon(path, m_body, 0, entry.Vertices.Length); }
public static Path NestPath2Path(NestPath nestPath) { Path path = new Path(); foreach (Segment s in nestPath.getSegments()) { ClipperCoor coor = CommonUtil.toClipperCoor(s.getX(), s.getY()); var lp = new IntPoint(coor.getX(), coor.getY()); path.Add(lp); } return(path); }
public Path ConnectedPath(WeightedGraph graph) { if (!Connected) { return(null); } Path result = new Path(front[0], false); for (int i = 0; i + 1 < front.Vertices.Count; i++) { if (front.Vertices[i] != commonVertex) { result.Add(front.Vertices[i + 1], graph.GetDistance(front[i], front[i + 1])); } } for (int i = back.Vertices.IndexOf(commonVertex); i > 0; i--) { result.Add(back.Vertices[i - 1], graph.GetDistance(back[i - 1], back[i])); } return(result); }
public static Path smoothPath(Path inputPath) { if (inputPath.Count <= 2) return inputPath; Path outputPath = new Path(); outputPath.Add(inputPath[0]); for (int i = 2; i < inputPath.Count - 1; ++i) { float distance = Vector3.Distance(outputPath[outputPath.Count - 1], inputPath[i]); // be careful with the direction of the ray Vector3 direction = (inputPath[i] - outputPath[outputPath.Count - 1]).normalized; if (Physics.Raycast(outputPath[outputPath.Count - 1], direction, distance, 1 << layerObstacles)) { outputPath.Add(inputPath[i - 1]); } } outputPath.Add(inputPath[inputPath.Count - 1]); return outputPath; }
private async void pathTimer_Tick(object sender, EventArgs e, Path path) { if (!MainWindow.localFound) { return; } var checkpointList = await Run(path.checkpointList); int id = checkpointList.Count + 1; if (checkpointList.Count == 0) { path.Add(id++); return; } if (checkpointList[checkpointList.Count - 1].DistanceFromMe(localPlayer) < 50f) //Make distance selectable { return; } path.Add(id++); }
public void AddPoints(string pathName, int interval, GatherWindow Gwindow) { if (Path.All(p => p.Name != pathName)) { Path.Add(new Paths(pathName)); Path.Last().AddPoints(interval, Gwindow); } else { Path.First(p => p.Name == pathName).AddPoints(interval, Gwindow); } }
public void TestPath() { Path points = new Path(); Point3D point = new Point3D(2, -5, 7); points.Add(point); Assert.AreEqual(2, point.X); Assert.AreEqual(-5, point.Y); Assert.AreEqual(7, point.Z); }
public void Replan() { Path.Clear(); int iterations = 0; //Begin psuedo code here //s_last = s_start s_last = s_start; Initialize(); //ComputeShortestPath() ComputeShortestPath(); //while s_start != s_goal while (s_start != s_goal) { if (iterations > maxIterations) { Debug.Log("Infinitely Looping"); return; } iterations++; //if g(s_start) = infinity, then there is no known path. if (double.IsPositiveInfinity(g[s_start])) { Debug.Log("No Known Path"); return; } Path.Add(s_start); //s_start = argmin s' element of succ(s_start) (c(s_start, s') + g(s')) List <State> succesors = Succ(s_start); double min = double.PositiveInfinity; State minState = null; foreach (State s in succesors) { double val = Cost(s_start, s) + g[s]; if (minState == null) { minState = s; min = val; } else { if (val < min) { min = val; minState = s; } } } s_start = minState; //Move to start; scan graph for any changed edge costs } }
public async Task <T> Get(string id) { var o = GetFromCache(id); if (o != null) { return(o); } o = await Store.Get <T>(Path.Add(id)); SetCache(id, o); return(o); }
// TODO: Optimize bytes public static Path Load(string file = DefaultFile) { Path path = new Path(); foreach (string line in File.ReadAllLines(file)) { foreach (Match item in Regex.Matches(line, @"X: (\d+), Y: (\d+), Z: (\d+)")) { int x = int.Parse(item.Groups[1].Value); int y = int.Parse(item.Groups[2].Value); int z = int.Parse(item.Groups[3].Value); path.Add(new Point3D(x, y, z)); } } return path; }
public static Path Load() { StreamReader reader = new StreamReader(@"d:/text.txt"); Path loadPath = new Path(); using (reader) { string line = reader.ReadLine(); while (line != null) { string[] extract = line.Split(','); Point3D pointLoaded = new Point3D(); pointLoaded.X = int.Parse(extract[0].Trim()); pointLoaded.Y = int.Parse(extract[1].Trim()); pointLoaded.Z = int.Parse(extract[2].Trim()); loadPath.Add(pointLoaded); line = reader.ReadLine(); } } return loadPath; }
public void Add_AddsSegment_ForSegment() { // Arrange // Act var sut = new Path(Point.Unknown); sut.Add(m_Segment1); // Assert Assert.AreEqual(1, sut.Segments.Count(), "Count"); Assert.AreEqual(m_Segment1, sut.Segments.First(), "First"); Assert.AreEqual(new Distance(1.0), sut.Distance, "Distance"); Assert.False(sut.IsUnknown, "IsUnknown"); }
// method that loads/saves the path from a file public static Path LoadPath(string fileName) { Path points = new Path(); using (StreamReader reader = new StreamReader(fileName)) { string line = reader.ReadLine(); while (line != null) { string[] linePoints = line.Split(' '); Struct3DPoint currentPoint = new Struct3DPoint(); currentPoint.X = int.Parse(linePoints[0]); currentPoint.Y = int.Parse(linePoints[1]); currentPoint.Z = int.Parse(linePoints[2]); points.Add(currentPoint); line = reader.ReadLine(); } } return points; }
//------------------------------------------------------------------------------ private void BuildResult(Paths polyg) { polyg.Clear(); polyg.Capacity = m_PolyOuts.Count; for (int i = 0; i < m_PolyOuts.Count; i++) { OutRec outRec = m_PolyOuts[i]; if (outRec.Pts == null) continue; OutPt p = outRec.Pts; int cnt = PointCount(p); if (cnt < 2) continue; Path pg = new Path(cnt); for (int j = 0; j < cnt; j++) { pg.Add(p.Pt); p = p.Prev; } polyg.Add(pg); } }
public void UpdateMouseWithLogicalCell(VectorInt2 cell, bool isLeftDown, bool isRightDown) { if (!Game.Current.Contains(cell)) return; peekMovePath = null; peekCratePath = null; try { if (Game.HasPendingMoves) { // No hints while there are outstanding actions return; } if (isLeftDown && !prevLeftDown) { Drag(cell); return; } if (!isLeftDown && prevLeftDown) { Drop(cell); return; } var peek = Peek(cell); if (peek != Action.None) { if (peek == Action.Move) { start = Game.Current.Player.Position; var end = cell; var boundry = Game.Current.ToMap(Game.Current.Definition.Wall, Game.Current.Definition.Crate, Game.Current.Definition.CrateGoal); peekMovePath = PathFinder.Find(boundry, start, end); } else if (peek == Action.Drag) { var end = cell; var state = Game.Analysis.Evalute(Game.Current); var pushMap = PushMap.Find(state.Static, state.Current, start, Game.Current.Player.Position); if (pushMap.CrateMap[end]) { //var walk = pushMap.FindPlayerWalkRoute(end); peekCratePath = pushMap.FindCrateRoute(end); // PLayer move to begin crate stuff var pstart = Game.Current.Player.Position; var pend = start - peekCratePath.First(); var boundry = Game.Current.ToMap(Game.Current.Definition.Wall, Game.Current.Definition.Crate, Game.Current.Definition.CrateGoal); peekMovePath = PathFinder.Find(boundry, pstart, pend); if (peekMovePath != null) { peekMovePath.Add(peekCratePath.First()); } } } } } finally { prev = cell; prevLeftDown = isLeftDown; prevRightDown = isRightDown; } }
//------------------------------------------------------------------------------ internal static Paths Minkowki(Path poly, Path path, bool IsSum, bool IsClosed) { int delta = (IsClosed ? 1 : 0); int polyCnt = poly.Count; int pathCnt = path.Count; Paths result = new Paths(pathCnt); if (IsSum) for (int i = 0; i < pathCnt; i++) { Path p = new Path(polyCnt); foreach (IntPoint ip in poly) p.Add(new IntPoint(path[i].X + ip.X, path[i].Y + ip.Y)); result.Add(p); } else for (int i = 0; i < pathCnt; i++) { Path p = new Path(polyCnt); foreach (IntPoint ip in poly) p.Add(new IntPoint(path[i].X - ip.X, path[i].Y - ip.Y)); result.Add(p); } Paths quads = new Paths((pathCnt + delta) * (polyCnt + 1)); for (int i = 0; i <= pathCnt - 2 + delta; i++) for (int j = 0; j <= polyCnt - 1; j++) { Path quad = new Path(4); quad.Add(result[i % pathCnt][j % polyCnt]); quad.Add(result[(i + 1) % pathCnt][j % polyCnt]); quad.Add(result[(i + 1) % pathCnt][(j + 1) % polyCnt]); quad.Add(result[i % pathCnt][(j + 1) % polyCnt]); if (!Orientation(quad)) quad.Reverse(); quads.Add(quad); } Clipper c = new Clipper(); c.AddPaths(quads, PolyType.ptSubject, true); c.Execute(ClipType.ctUnion, result, PolyFillType.pftNonZero, PolyFillType.pftNonZero); return result; }
//------------------------------------------------------------------------------ public static Path CleanPolygon(Path path, double distance = 1.415) { //distance = proximity in units/pixels below which vertices //will be stripped. Default ~= sqrt(2) so when adjacent //vertices have both x & y coords within 1 unit, then //the second vertex will be stripped. double distSqrd = (distance * distance); int highI = path.Count -1; Path result = new Path(highI + 1); while (highI > 0 && PointsAreClose(path[highI], path[0], distSqrd)) highI--; if (highI < 2) return result; IntPoint pt = path[highI]; int i = 0; for (;;) { while (i < highI && PointsAreClose(pt, path[i], distSqrd)) i+=2; int i2 = i; while (i < highI && (PointsAreClose(path[i], path[i + 1], distSqrd) || SlopesNearCollinear(pt, path[i], path[i + 1], distSqrd))) i++; if (i >= highI) break; else if (i != i2) continue; pt = path[i++]; result.Add(pt); } if (i <= highI) result.Add(path[i]); i = result.Count; if (i > 2 && SlopesNearCollinear(result[i - 2], result[i - 1], result[0], distSqrd)) result.RemoveAt(i -1); if (result.Count < 3) result.Clear(); return result; }
internal static Path PointFArrayToIntArray(PointF[] points, float scale) { Path result = new Path(); for (int i = 0; i < points.Length; ++i) { result.Add(new IntPoint((int)points[i].X * scale, (int)points[i].Y * scale)); } return result; }
public void ToString_ReturnsString() { // Arrange var line = new Line(-10.0, -10.0, 10.0, 10.0); Polyline polyline = CreatePolyline(); polyline.AddSegment(line); var sut = new Path(polyline); sut.Add(m_Segment1); const string expected = "Length: 29.28"; // Act string actual = sut.ToString(); // Assert Assert.AreEqual(expected, actual); }
public Path ConnectedPath(WeightedGraph graph) { if (!Connected) return null; Path result = new Path(front[0], false); for (int i = 0; i + 1 < front.Vertices.Count; i++) if (front.Vertices[i] != commonVertex) result.Add(front.Vertices[i + 1], graph.GetDistance(front[i], front[i + 1])); for (int i = back.Vertices.IndexOf(commonVertex); i > 0; i--) result.Add(back.Vertices[i - 1], graph.GetDistance(back[i - 1], back[i])); return result; }
public static Path LoadPaths(string pathFromFile) { Path pointsPath = new Path(); try { Encoding win1251 = Encoding.GetEncoding("Windows-1251"); StreamReader reader = new StreamReader(pathFromFile, win1251); using (reader) { string line = reader.ReadLine(); while (line != null) { pointsPath.Add(ParseLineToPoint(line)); line = reader.ReadLine(); } } } catch (Exception exeption) { Console.WriteLine(exeption.Message); } Console.WriteLine("Reading from file successfully finished!"); return pointsPath; }
static Path RectangleToPath(RectangleF rect) { Path path = new Path (); path.Add(new IntPoint(rect.Left * scale, rect.Top * scale)); path.Add(new IntPoint(rect.Right * scale, rect.Top * scale)); path.Add(new IntPoint(rect.Right * scale, rect.Bottom * scale)); path.Add(new IntPoint(rect.Left * scale, rect.Bottom * scale)); path.Add(new IntPoint(rect.Left * scale, rect.Top * scale)); return path; }
//------------------------------------------------------------------------------ public PolyOffsetBuilder(Paths pts, out Paths solution, double delta, JoinType jointype, EndType endtype, double limit = 0) { //precondition: solution != pts solution = new Paths(); if (ClipperBase.near_zero(delta)) {solution = pts; return; } m_p = pts; if (endtype != EndType.etClosed && delta < 0) delta = -delta; m_delta = delta; if (jointype == JoinType.jtMiter) { //m_miterVal: see offset_triginometry.svg in the documentation folder ... if (limit > 2) m_miterLim = 2 / (limit * limit); else m_miterLim = 0.5; if (endtype == EndType.etRound) limit = 0.25; } if (jointype == JoinType.jtRound || endtype == EndType.etRound) { if (limit <= 0) limit = 0.25; else if (limit > Math.Abs(delta)*0.25) limit = Math.Abs(delta)*0.25; //m_roundVal: see offset_triginometry2.svg in the documentation folder ... m_Steps360 = Math.PI / Math.Acos(1 - limit / Math.Abs(delta)); m_sin = Math.Sin(2 * Math.PI / m_Steps360); m_cos = Math.Cos(2 * Math.PI / m_Steps360); m_Steps360 /= Math.PI * 2; if (delta < 0) m_sin = -m_sin; } double deltaSq = delta * delta; solution.Capacity = pts.Count; for (m_i = 0; m_i < pts.Count; m_i++) { int len = pts[m_i].Count; if (len == 0 || (len < 3 && delta <= 0)) continue; if (len == 1) { if (jointype == JoinType.jtRound) { double X = 1.0, Y = 0.0; for (cInt j = 1; j <= Round(m_Steps360 * 2 * Math.PI); j++) { AddPoint(new IntPoint( Round(m_p[m_i][0].X + X * delta), Round(m_p[m_i][0].Y + Y * delta))); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } } else { double X = -1.0, Y = -1.0; for (int j = 0; j < 4; ++j) { AddPoint(new IntPoint(Round(m_p[m_i][0].X + X * delta), Round(m_p[m_i][0].Y + Y * delta))); if (X < 0) X = 1; else if (Y < 0) Y = 1; else X = -1; } } continue; } //build normals ... normals.Clear(); normals.Capacity = len; for (int j = 0; j < len -1; ++j) normals.Add(GetUnitNormal(pts[m_i][j], pts[m_i][j+1])); if (endtype == EndType.etClosed) normals.Add(GetUnitNormal(pts[m_i][len - 1], pts[m_i][0])); else normals.Add(new DoublePoint(normals[len - 2])); currentPoly = new Path(); if (endtype == EndType.etClosed) { m_k = len - 1; for (m_j = 0; m_j < len; ++m_j) OffsetPoint(jointype); solution.Add(currentPoly); } else { m_k = 0; for (m_j = 1; m_j < len - 1; ++m_j) OffsetPoint(jointype); IntPoint pt1; if (endtype == EndType.etButt) { m_j = len - 1; pt1 = new IntPoint((cInt)Round(pts[m_i][m_j].X + normals[m_j].X * delta), (cInt)Round(pts[m_i][m_j].Y + normals[m_j].Y * delta)); AddPoint(pt1); pt1 = new IntPoint((cInt)Round(pts[m_i][m_j].X - normals[m_j].X * delta), (cInt)Round(pts[m_i][m_j].Y - normals[m_j].Y * delta)); AddPoint(pt1); } else { m_j = len - 1; m_k = len - 2; m_sinA = 0; normals[m_j] = new DoublePoint(-normals[m_j].X, -normals[m_j].Y); if (endtype == EndType.etSquare) DoSquare(); else DoRound(); } //re-build Normals ... for (int j = len - 1; j > 0; j--) normals[j] = new DoublePoint(-normals[j - 1].X, -normals[j - 1].Y); normals[0] = new DoublePoint(-normals[1].X, -normals[1].Y); m_k = len - 1; for (m_j = m_k - 1; m_j > 0; --m_j) OffsetPoint(jointype); if (endtype == EndType.etButt) { pt1 = new IntPoint((cInt)Round(pts[m_i][0].X - normals[0].X * delta), (cInt)Round(pts[m_i][0].Y - normals[0].Y * delta)); AddPoint(pt1); pt1 = new IntPoint((cInt)Round(pts[m_i][0].X + normals[0].X * delta), (cInt)Round(pts[m_i][0].Y + normals[0].Y * delta)); AddPoint(pt1); } else { m_k = 1; m_sinA = 0; if (endtype == EndType.etSquare) DoSquare(); else DoRound(); } solution.Add(currentPoly); } } //finally, clean up untidy corners ... Clipper clpr = new Clipper(); clpr.AddPaths(solution, PolyType.ptSubject, true); if (delta > 0) { clpr.Execute(ClipType.ctUnion, solution, PolyFillType.pftPositive, PolyFillType.pftPositive); } else { IntRect r = clpr.GetBounds(); Path outer = new Path(4); outer.Add(new IntPoint(r.left - 10, r.bottom + 10)); outer.Add(new IntPoint(r.right + 10, r.bottom + 10)); outer.Add(new IntPoint(r.right + 10, r.top - 10)); outer.Add(new IntPoint(r.left - 10, r.top - 10)); clpr.AddPath(outer, PolyType.ptSubject, true); clpr.ReverseSolution = true; clpr.Execute(ClipType.ctUnion, solution, PolyFillType.pftNegative, PolyFillType.pftNegative); if (solution.Count > 0) solution.RemoveAt(0); } }
private void RegisterNodesPages( Path<INavigationTreeNode> parentPath, IEnumerable<INavigationTreeNode> nodes) { foreach (var node in nodes) { if (_pageNodeMap.ContainsKey(node.NavigationPageName)) throw new ApplicationException( "Страница навигации '{0}' указана в нескольких элементах дерева навигации." .FormatStr(node.NavigationPageName)); var nodePath = parentPath.Add(node); _pageNodeMap.Add(node.NavigationPageName, nodePath); RegisterNodesPages(nodePath, node.Childrens); } }
//------------------------------------------------------------------------------ internal static bool StripDupsAndGetBotPt(Path in_path, Path out_path, bool closed, out IntPoint botPt) { botPt = new IntPoint(0, 0); int len = in_path.Count; if (closed) while (len > 0 && (in_path[0] == in_path[len -1])) len--; if (len == 0) return false; out_path.Capacity = len; int j = 0; out_path.Add(in_path[0]); botPt = in_path[0]; for (int i = 1; i < len; ++i) if (in_path[i] != out_path[j]) { out_path.Add(in_path[i]); j++; if (out_path[j].Y > botPt.Y || ((out_path[j].Y == botPt.Y) && out_path[j].X < botPt.X)) botPt = out_path[j]; } j++; if (j < 2 || (closed && (j == 2))) j = 0; while (out_path.Count > j) out_path.RemoveAt(j); return j > 0; }
public void AStar(Vector3 start, Vector3 end, OnPathComputed callback) { // Reset all scores and sets membership Reset(); Node startNode = getClosestNode(start); Node endNode = getClosestNode(end); if (startNode == null || endNode == null) { callback(new Path()); return; } PriorityQueue<Node> openSet = new PriorityQueue<Node>(); openSet.Push(startNode); startNode.InOpenSet = true; Dictionary<Node, Node> parentPath = new Dictionary<Node, Node>(); startNode.GScore = 0; startNode.FScore = startNode.GScore + heuristic(startNode, endNode); Path path = new Path(); Node current = startNode; while (openSet.Count() > 0) { current = openSet.Pop(); // automatically do the remove part current.InOpenSet = false; if (current.Id == endNode.Id) { path.Add(current.Position); while (parentPath.ContainsKey(current)) { current = parentPath[current]; path.Add(current.Position); } path.Reverse(); callback(path); return; } current.InClosedSet = true; List<Node> neighbors = getNeighbors(current); for (int i = 0; i < neighbors.Count; ++i) { Node neighbor = neighbors[i]; if (neighbor.InClosedSet) continue; float gAttempt = current.GScore + euclidian(current, neighbor); if (!neighbor.InOpenSet || gAttempt <= neighbor.GScore) { parentPath[neighbor] = current; neighbor.GScore = gAttempt; neighbor.FScore = neighbor.GScore + heuristic(neighbor, endNode); if (!neighbor.InOpenSet) { openSet.Push(neighbor); neighbor.InOpenSet = true; } } } // end loop neighbors } }
public void Length_ReturnsThree_ForPathWithThreePoints() { // Arrange // Act var sut = new Path(m_Segment1.StartPoint); sut.Add(m_Segment1); sut.Add(m_Segment2); // Assert Assert.AreEqual(3.0, sut.Distance.Length); }